我正在使用urlclass加载程序在运行时加载一个jar文件。Jar文件和类正在成功加载。我有一个具有返回对象X的方法的类。使用对象X,我必须调用X上的Setter方法。
如何在X上调用setter方法?
我通过调用方法返回对象X。
X = my.invoke(inst, obj);newInstance()方法再次创建实例?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;
}
}
}发布于 2014-02-28 21:52:26
是否需要通过调用X类上的newInstance()方法再次创建实例?
不,考虑到您的解释,您已经有了一个对象X。您不需要创建任何类型的新对象。
要调用对象X的方法,必须每次调用method.invoke()吗?假设X对象有5个方法,查找该方法并使用Method.invoke调用该方法。
反射是运行时的事情。您不知道要使用的声明(或静态)类型。基本上,您只使用Object接口/契约。因此,您需要通过反射实用程序来完成所有工作。如果要调用对象的方法,则需要检索相应的Method对象并使用正确的参数调用其invoke(..)方法。
发布于 2014-02-28 22:06:41
这取决于定义X类的类加载器。如果是父类加载程序,则可以简单地转换返回值:
X x = (X) my.invoke(inst, obj);然后像其他java对象一样使用它。
如果X是由自定义类加载器定义的,则会变得更加复杂,因为由父类加载器加载的类看不到X的定义。因此,这些类不能在其源代码中引用X的方法和字段。通常的解决方法是在由X在自定义类加载器中实现的父类加载器中有一个接口(让我们称之为Y)。由于这些方法是在Y中声明的,所以可以从父类加载器访问它们,即使调用它们执行类X中的实现。
如果您也不能这样做,仍然可以使用反射调用这些方法。
https://stackoverflow.com/questions/22106270
复制相似问题