Question

I am new in the forum and pretty new about Java coding.

Anyway I am implementing my Java code to dynamically compile and run different classes which are not know a priori and which could change over time (not too frequently). I fount very useful the example proposed here based on javax.tools but, since my work should run on real-time later, I would like to avoid as much as possible to use Java reflection. Do you know if exists a way to run the compiled code without use reflation? There are some variable that I can retrieve after the compilation which points to the class and then use it to instantiate the class?

thanks is advance Luca

Était-ce utile?

La solution

Hey so look i dunno if this is right or this is what you want but i would divide the framework as such ...

The interface interface is just for easier understanding.

public interface fun {
void fun();
}

so lets say someone builds the code for your app or framework ... give him your interface and tell him to put functionality in that method .. which would be something like this ..

public class TestDestination implements test.fun {
public void fun(){

    System.out.println("Hello");

}
}

then all you have to do is load this class ... you can get the name from user input xml etc etc... this will be your executer

public class TestLoad {
public static void main(String[] args) {
    try {
        Class t1 = Class.forName("test.temp.TestDestination");
        fun temp = (fun) t1.newInstance();
        temp.fun();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

i am not sure if this is exactly what you want ... but it would be ideal to keep the loader on a separate thread and load all classes that you want in the beginning of your program or lazy load it ... your choice hope this helps i am assuming that class.forName is efficient ... correct me if wrong

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top