正在创建已加载类的实例



我对类加载器这个问题还很陌生,我有一个问题:我在类文件中有一个类(已编译,没有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类的一个实例,并从中调用一些公共方法。这可能吗?

您可以创建实例并调用方法,如下所示:

您已经在使用自己的类加载器,因此方法loadClass("Hidden")将返回引用您的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");将给出引用Your类Hidden的Class类对象。使用此引用,您可以获得所有字段、方法、构造函数,并且可以根据需要使用它们。

最新更新