Is it possible to open a .txt / .java file containing a class and use reflection on it?

What I mean by this is opening a file with Java code in it as a class, not as a file. So basically I want:

-> Open a clean text file in a self-written Java application (.txt / .log / .java) -> Recognize the class in the file, for example:

public class TestExample { private String example; public String getExample() { return example; } } 

I will open it in a handwritten program. Instead of recognizing the text in the file as String or as plain text, it will find the TestExample class in it. Then he will save it as a class.

-> Use the Reflection API for the class -> Get fields, methods, etc. From file and display them

Is it possible?

+4
source share
4 answers

Yes it is possible.

Take a look at this example.

http://weblogs.java.net/blog/malenkov/archive/2008/12/how_to_compile.html

Knowing how to find and read files (which is very simple), you can use the code shown, especially

 javax.tools.JavaCompiler javax.tools.ToolProvider.getSystemJavaCompiler() 

to compile the code and then call it using reflection.

+2
source

You can compile Java code on the fly. See Example: How can I compile the java source contained in String on the fly?

Create a class loader and use reflection

+1
source

You might want to watch Beanshell .

+1
source

I know this is old, but I wanted to add to the stream:

Yes it is possible. Basically you use the JavaCompiler class in java to compile any string at runtime and return an instance of java.lang.Class that can be used to instantiate the object.

I wrote a small minimal library for the project I'm currently working on. Feel free to use the library as you wish. EzReflection allows you to fully compile code in memory without requiring you to write a .class file.

Using ezReflections, the code would look like this:

 InMemoryEzReflectionsCompiler compiler = new InMemoryEzReflectionsCompiler(); String src = new Scanner(new File("filename")).useDelimiter("\\Z").next(); Class<?> cls = compiler.compileClass("name of class", src); // if your class doesn't require arguments in the constructor cls.newInstance(); // if your class requires arguments for the constructor. Here assuming one Integer and one double Constructor<?> cons = cls.getConstructor(new Class[]{Integer.class,double.class}); Object obj = cons.newInstance(new Object[]{(int)10,(double)9}); 

You can also find a set of tutorials on the Github page on how to use ezReflections.

0
source

Source: https://habr.com/ru/post/1403416/


All Articles