문제

Hi still learn some concepts in java. so sorry if this is a silly question

I Have a class in a jar. i am loading it to my class path dynamically using reflection. and then i am calling the classes constructor method like so :

        File jar = new File("C:\\Users\\JG\\Desktop\\testAlgorithm.jar");

        URL url = jar.toURI().toURL();            
        URL[] urls = new URL[]{url};

        ClassLoader cl = new URLClassLoader(urls);           
        Class classToLoad = Class.forName ("testAlgorithm.Stock", true, cl);

        Method[] m = classToLoad.getDeclaredMethods();
       Class[] cArg = new Class[1];            
        cArg[0] = String.class;

         Method method = classToLoad.getDeclaredMethod("Stock",cArg);  

         Object result = method.invoke (instance, appl , start , end, 800, 30   );

so i am using method.invoke() to call the constructor, as a method. I want to use the class's setters ( eg stock.setDate() etc. . ) How do i do this ?

Have looked at other posts & someone has suggested the Commons BeanUtils package ? Best way of invoking getter by reflection

I would like to know if BeanUtils the Is this the simplest why to do this, or if i am missing some obvious functionality provided by javas classloader and class object ?

Thank you guys !

Edit : More Info. - add a bit of context.

The context is i have a PLay web server, & i am letting user uoload Jars to the server, for the server to use the classes in the uploaded jars.

Server will display the returned results of functions of classes in the uploads jars, after they have been run on the server, on a web page.

도움이 되었습니까?

해결책

Do you mean somenthing like this:

try{
    Class<?> klass = Class.forName("[classname]");
    object = ([ObjectType]) klass.newInstance();

    String methodName = "setAddress"; //for example
    Method method = object.getClass().getMethod(methodName, java.lang.String.class);

    method.invoke(object, "[address]");
} catch(NoSuchMethodException e){
    e.printStackTrace();
}

* replace the [] with your values

다른 팁

Assuming java 7. Assuming Stock is the class and testAlgorithm the package (convention is only small letters and seldom '_').

Then it would go as:

Constructor c =  classToLoad.getContructor(String.class, int.class,
    boolean.class); // Any number of classes for constructor parameters.
Object obj = c.newInstance("", 3, true);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top