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

我们两清 提交于 2021-02-19 02:23:29

问题


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

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

public class TestExample { 
private String example; 

public String getExample() { 
return example; 
} 
} 

I will open this in a hand-written program. Instead of recognizing the text in the file as a String or as pure text, it will find the class TestExample in it. Then it will save this as a Class.

-> Use the Reflection API on the class -> Get fields, methods, etc from file and display them

Would this be possible?


回答1:


Yes, it is possible.

Have 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 really simple), you can then use the code shown, especially

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

to compile the code and then call it using reflection.




回答2:


You can compile java code "on the fly". See example: How do I on-the-fly compile a java source contained in a String?

The create classloader and use reflection




回答3:


You might want to look at Beanshell.




回答4:


I know this is old but wanted to add to the thread:

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

I have written a small, minimal library for a project that I'm currently working on. Feel free to use the library as you wish. EzReflection lets you compile a code completely in memory not requiring you to write the .class file.

Using ezReflections you code will 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 tutorial on the Github page on how to use ezReflections.



来源:https://stackoverflow.com/questions/9868892/is-it-possible-to-open-a-txt-java-file-containing-a-class-and-using-reflectio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!