How to run .java file with Variable Name

2019-07-14 07:02发布

I'm trying to make a program based off of the Pebble Smartwatch Operating System. I have a text file called PebbleOS_Faces.txt which has all the names of the different watch faces I will have on the watch.

I use PrintWriter to convert the content into a .java file, and then I compile it using the code I got from this post. It gets compiled into the build/classes/pebbleos folder (I'm using Netbeans for Mac, in case that makes a difference), next to all of the other classes. I've confirmed that this all works properly.

What's left is for me to actually run the class from inside the program. The thing is, each class would have a different name based off of the names of the watch faces in the PebbleOS_Faces.txt file. How do I create an instance of a class that has a variable name?

标签: java class
2条回答
2楼-- · 2019-07-14 07:11

You'll want to use Reflection. You can get a Class object by name using Class.forName(String). You can call the constructor with Class.getConstructors()[0].newInstance(<insert constructor arguments here>)*. Make sure all the classes inherit a common superclass so that you can do something like:

WatchFace face = Class.forName(watchFaceName).getConstructors()[0].newInstance();

*This is assuming there is only one constructor

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-14 07:29

I've never tried this with dynamically generated/compiled classes, but...

Try using Class.forName("com.example.YourClassName") to get a reference to the Class:

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)

and then use Class.newInstance() to create an instance of the class:

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance()

For this to work, com.example.YourClassName would have to be visible to your class loader.

For example:

Class clazz = Class.forName("com.example.YourClassName");
Object instance = clazz.newInstance();

The newInstance() call will only work if your class has a no-argument constructor.

If the YourClassName class's constructor requires arguments you must use a slightly different technique to call a specific constructor and pass values into it. For example, if you had a constructor like this:

YourClassName(Integer someInt, String someString)

Then you could do this to instantiate YourClassName via that constructor:

Class clazz = Class.forName("com.example.YourClassName");
Constructor constructor = clazz.getConstructor(Integer.class, String.class);
Object instance = constructor.newInstance(anInteger, "aString");

It would probably help if every instance of YourClassName implemented the same interface or extended the same base class so that you could cast the return value of newInstance() to that interface or base class. Then you would be able to call the interface or base class's methods on the instance. Otherwise, your only way to call useful methods on the Object would be to use reflection.

查看更多
登录 后发表回答