我正在运行时使用 urlclassloader 加载 jar 文件。 Jar 文件和类已成功加载。 我有一个类,它的方法返回一个对象 X。 使用对象 X,我必须在 X 上调用 Setter 方法。
如何调用 X 上的 setter 方法?
我通过调用该方法返回了对象 X。
X = my.invoke(inst, obj);
- 我需要通过调用 X 类上的
newInstance()
方法再次创建实例吗? - 要调用对象 X 的方法,我是否必须每次都调用
method.invoke()
? 假设X对象有5个方法,找到该方法并使用Method.invoke调用该方法。
您的建议将会非常有帮助。
File f1 = new File("/home/egkadas/CR364/lib/xxx.jar");
URL urls [] = new URL[1];
urls[0] = f1.toURL();
URLClassLoader urlClass = URLClassLoader.newInstance(urls);
Class c1 = urlClass.loadClass("com.xxxx.example.poc.Container");
Container inst = (Container)c1.newInstance();
if(inst == null){
System.out.println("Object is null");
}else{
Method my = c1.getMethod("getAttribute",null);
Object[] obj = new Object[0];
com.XXXXX.example.poc.Container.Attributes att =(com.XXXXX.example.poc.Container.Attributes)my.invoke(inst, obj);
System.out.println(att);
jar 中的代码:
public class Container {
public String id;
public Container(){
}
public Container(String id){
this.id=id;
}
public void setId(String id){
this.id=id;
}
public Attributes getAttribute(){
return new Attributes("check","12lb","15lb",100);
}
public List<Attributes> getAttributes(){
List<Attributes> ats = new ArrayList<Attributes>();
return ats;
}
public static class Attributes {
public String name;
public String weight;
public String height;
public int capacity;
public Attributes(String name,String weight,String height,int capacity){
this.name=name;
this.weight=weight;
this.height=height;
this.capacity=capacity;
}
public Attributes(){
}
public String toString(){
return this.name+" "+this.weight+" "+this.height+" "+this.capacity;
}
public void setName(String name){
this.name=name;
}
public void setWeight(String weight){
this.weight =weight;
}
public void setHeight(String height){
this.height=height;
}
public void setCapacity(int cap){
this.capacity=cap;
}
}
}
最佳答案
Do I need to create an instance again by calling newInstance() method on X class?
不,根据您的解释,您已经有了一个对象 X。您不需要创建一个新的对象,无论它是什么类型。
To call the methods of Object X, Do i have to call method.invoke() each and every time ? Assume X object has 5 methods, find the method and invoke the method using Method.invoke.
反射是运行时的事情。您不知道要使用的声明(或静态)类型。您基本上只使用 Object
接口(interface)/合约。因此,您需要通过反射实用程序完成所有操作。如果要调用对象的方法,则需要检索相应的 Method
对象并使用正确的参数调用其 invoke(..)
方法。
关于Java 类加载和反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22106270/