Search code examples
javareflectionbindingscriptengine

Can reflection bind a class to a new name?


I am trying to let users of my program rename classes and methods in the class. The new names can be read in and configured at run time and they will call these classes and methods in a scripting language using Java Script Engine. I need a way to bind their new names to the real names of the classes and methods. I have been looking at Reflection but I do not think this can provide me with the capability I need, or is this even possible?

Ex:

public class RealName {
    public void printHello() {
        System.out.println("Hello");
    }
}

Then in maybe Paython say

obj = new NewName()
obj.hello()

Tell me if this is impossible please!


Solution

  • To answer my question from what I've found no you cannot use reflection to bind a class to a new name. In fact I found no easy way to do dynamic renaming.

    What I did to overcome this was to write code from a string to a file, save that file with extension .java, compile that file, then use it with reflection or better yet use it inside a script using the Java ScriptEngine API (that way you can avoid the ugly reflection code and actually have everything dynamic and on the fly).

    Here's a starting point for creating the file,

    Dynamic in-memory compilation

    And here's something for scripting Java,

    Scripting for Java