placeholder for any code - java

I need to define a object at runtime like below.
Filter rowFilter = new RowFilter(CompareFilter.CompareOp.EQUAL,
new RegexStringComparator(".*-.5"));
I am reading one String which is having code like below
String _filterString = "RowFilter(CompareFilter.CompareOp.EQUAL,
new RegexStringComparator(\".*-.5\"))";
Now I need to define a filter object by using the above String.
I know, this type of problems we can achieve by using Reflections.But I am looking for alternatives. Is there any simple way to solve problems like this?

The Java Scripting API allows embedding of miscellaneous languages like JavaScript and have bindings to Java variables and methods. In your case the language BeanShell (Java subset) can be used.

Java Compiler can be used for compiling at Runtime, but it requires a full source (Compilation Unit). I don't think a single expression can be compiled. Maybe, you can work out from here to get your objects from the classes compiled at runtime.

Related

Simulating C/C++ empty defines in Java

I know Java does not have pre-processor, but I struggle to find a way to do this.
I am looking to create macros to improve code readibility, to specify which of the functions or parameters are for input or output specifically. In C, this would be done like this :
#define IN
#define OUT
And these would just be used before the variables and functions. Can I simulate the same behavior in Java?
I did not manage to find a way to do this. The only way I found was including defines in the code and first using the cpp pre-processor to replace them, and then run the java code, but maybe there is a better way of doing this?
Java indeed does not have a pre-processor, and your use case doesn't require that either: you aren't actually preprocessing the code, you just put in some tags that the compiler can ignore.
What you are looking for are "annotations" - you basically want to annotate your code with some nice text that will not affect the compiler.
This basically requires defining some specialized Java types for this using the #interface keyword and then you can use them to write things like:
public void doStuff(#Input invar, #Output outvar) {
...
These annotations can be simply:
#interface Input {}
#interface Output {}
or you can add more features and even use reflection to examine them in runtime.
See the linked documentation above for more details.

Can you dynamically rename a class name?

Is it possible in Java to give a class or even its functions a new name at run time. By reading in the new names as arguments or on a configuration file when the program is started?
UPDATE:
Here is the purpose of this. I am using Java Script Engine to allow any JSR 223 compatible Scripting Language to access our API. Some of our clients are not used to using Java and it's naming conventions and would feel more comfortable using their own specific naming conventions. So I am required to give them the capability to dynamically change the API's class and function names without actually changing them in the code. It was suggested I use a Map and some sort of binding with a string name and the actual Java name e.g.,
map.put("Hello",HelloWorld.class)
Object obj = new Hello();
which should be the same as,
Object obj = new HelloWorld();
If this is not possible please tell me why. I need a solid Java expertise answer. This is out of my league and I need facts to tell people why this is not possible even though myself I am almost sure it's not possible.
Possible Solution:
Here is the closets solution I have come up with. Using this link,
https://weblogs.java.net/blog/2005/08/10/reflection-and-dynamically-changing-classes
I could add in the names at run time, use composition to create an Adapter Class, and then compile the file, and voila the Script Language folks could use their defined names instead of my API's Java names.
Is this the only conceivable way to accomplish this?
UPDATE 2:
Here is another possible solution for anyone trying this too,
http://asm.ow2.org/doc/faq.html
That'll take you directly to their frequently asked questions which will have one for this exact problem.
No, you will need to refactor for references and recompile for execution.
Yes, you are able to do that using javassist.
In particular, you have to edit NewExpr.

Will Java have a way for non-library developers to use extension methods?

C#'s extension methods are great for adding syntactic sugar. Java extension methods are great for allowing library developers to add methods to their interfaces.
I am a non-library Java developer and know I will reap a lot of benefits from getting new functionality from libraries, but I would still like to have the syntactic sugar capabilities of C# extension methods.
Is this, or will this be possible in future versions of Java?
eg: I would like to add methods to the String class...
String data = StringUtils.capitalize("abcd"); // instead of this
String data = "abcd".capitalize() // I would like to do this
Please don't focus on this particular example, I am only showing the class of functionality I want to be able to achieve.
Java does not have this feature, nor is it likely to have it anytime soon.
Groovy however does have a very similar feature, and it also runs on the JVM. Perhaps that's an option.
I suspect you're thinking of a planned addition to Java 8 that will allow you to add methods, with default implementations, to an interface -- so that you can add new methods without breaking all existing code. This is only of use to you if you control the interface type -- so it would not be of use for String, because String is not an interface.

Is Compiling String as code possible?

I have an app that gets the content of an html file.
Lets say the text of the page is:
String[] arr = new String[] {"!","#","#"};
for (String str : arr) {
write(str);
}
Can I somehow compile this text and run the code within my app?
Thanks
Use Janino. It's a java runtime in-memory compiler. Way easier than BCEL and the likes.
From the homepage:
"What is Janino?
Janino is a super-small, super-fast Java™ compiler. Not only can it compile a set of source files to a set of class files like the JAVAC tool, but also can it compile a Java™ expression, block, class body or source file in memory, load the bytecode and execute it directly in the same JVM. Janino is not intended to be a development tool, but an embedded compiler for run-time compilation purposes...
You can use the javac compiler, or the Java Compiler API or the BeanShell library (or similar). You can compile it any number of ways, none terribly simple which often leads to finding another way to solve your problem.
Instead of generating source and compiling its common to generate byte code directly using ASM, Javaassist, BCEL or the like
This appears to be the same as
for(char ch: "!##".toCharArray())
write(ch);
which is likely to be the same as
write("!##");
Since the question is tagged android:
The answers posted so far only apply to the “standard” JVM, not to Android's Dalvik VM. In principle, it is possible on Android too. I don't know if there's an existing Java compiler that you can embed, but you would probably generate the final Dalvik bytecode using dexmaker. It may be possible to combine an existing Java compiler with dexmaker.
But please think twice before attempting anything like this, and be very careful. The last thing you want is a way for an attacker to execute arbitrary code on your user's hardware.
You can try javassist, it's not full Java though.
This is not usually that hard to do, but I have to ask can you give more detail on exactly what it is you are trying to accomplish. I do this type thing all the time. This is just another example of getting information from the user and using it somewhere else in your code. Since your using java maybe look at the string API http://docs.oracle.com/javase/6/docs/api/java/lang/String.html and the string tokenizer http://docs.oracle.com/javase/6/docs/api/index.html?java/lang/package-summary.html
Now you can break the string down into single values one word or other value at a time. From there you can use functions such as isNAN() from the float or double class to determine if it a number or string or whatever it is your testing for. Now you know what you’re dealing with you can reconstructed the data in a usable form.
Note for values if you want to use them as values use Float(string value) constructor. i.e Float x = new Float(myString)

Java API to get metadata about Java Source Code

I would like to create some reverse egineered design docs based on Java code (not bytecode), instead of writing my own interpreter, what tools and APIs are available to traverse Java code, using Java code?
Reflection is on bytecode, and is limited to the method level, I want to "objectize" also the method code.
Java doc is ignoring the code itself and only based on comments, automatic UML sequnces are too strict
E.g. an API like this (forgive my ignorance of official Programming Languages Structure terms):
JavaCodeDom jcd = new JavaCodeDom(new File(pathToJavaSource), CompilerEnum.Java16)
List <ClassSrc> classes = jcd.getClasses();
ClassSrc cls = classes.get(0);
Map<MethodSignatureSrc,MethodSrc> methods = cls.getMethodsMap();
MethodSrc main = mothds.get(new MethodSignatureSrc(Modifiers.Public, Modifiers.Static, ReturnTypes.Void, "main", new MethodParams(String[].class))
List<StatementSrc> statements = main.getStatements();
for(StatementSrc statement : statements){
if(statement.getType()==StatementTypes.Assignment()){
AssignmentStatementSrc assignment = (AssignmentStatementSrc)statement;
Identifier src = assignment.getAssigneeVariable();
ExpressinoSrc = assignment.getAssignmentValue();
}
}
List<AnnotationsSrc> annotations = cls.getAnnotations();
There are several such APIs in existence (and delivered with the JDK), some of them build in in the Java Compiler (javac).
The most extensive is the Compiler Tree API, which gets you access to individual expressions (and subexpressions) in the Java source.
The language model API models types and members of types (constructors, methods, fields) - it is used by the compiler tree API and also for annotation processing. It does not give access to the contents of the methods.
Of course, on runtime you have the Reflection API (java.lang.Class and java.lang.reflect.*, together with java.lang.annotation).
To use the compiler tree API, you have to invoke the compiler, with the compiler API.
Additionally, there is the Doclet API for Javadoc, which gives you a similar view like the language model API, but additionally with the documentation comments (and parsed tags).
I once used a combination of Doclet API and Compiler Tree API to format source code beautifully (this is not online, sadly).
BCEL supports reading an manipulating Java class files. (I have not used it myself, but saw it used successfully in a third-party product.)
The Byte Code Engineering Library is intended to give users a convenient
possibility to analyze, create, and manipulate (binary) Java class files
(those ending with .class). Classes are represented by objects which
contain all the symbolic information of the given class: methods,
fields and byte code instructions, in particular.
If you're just interested in decompiling, you might find it sufficient to decompile to source code. Here's a comparison of several options for Java.
I seems ANTLR is one option, but I haven't used it
This seems to answer my question: How to generate AST from Java source-code? ( Spoon )

Categories