我对类加载器很新有问题并且有一个问题是否可行:我在类文件中有一个类(编译,没有src代码) - Hidden.class。我有一个自定义类加载器,可以加载这样的类:
CustomClassLoader loader = new CustomClassLoader();
// load class
try {
loader.loadClass("Hidden");
// instantiate the class here and use it
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
我想创建一个这个Hidden类的实例,并从中调用一些公共方法。有可能吗?
答案 0 :(得分:3)
您可以创建实例和调用方法,如下所示:
您已经在使用自己的类加载器,因此方法 loadClass(“Hidden”)将返回引用Your Hidden类的Class类对象。
try {
Class<?> c = loader.loadClass("Hidden"); // create instance of Class class referring Hidden class using your class loader object
Object t = c.newInstance();// create instance of your class
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {// get methods
String mname = m.getName();// get method name
try {
m.setAccessible(true);
m.invoke();//change as per method return type and parameters
} catch (InvocationTargetException x) {
// code here
}
}
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
} catch (InstantiationException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}
此处Class.forName("Hidden");
将提供引用您的班级Hidden
的Class类对象。使用此引用,您可以获得所有字段,方法和构造函数,并且可以根据需要使用它们。