简体   繁体   中英

Creating instances of loaded classes

I am quite new to the class loader problematic and have a question whether this would be possible: I have a class in a class file (compiled, no src code) - Hidden.class. I have a custom class loader which is able to load the class like this:

        CustomClassLoader loader = new CustomClassLoader();

        // load class
        try {
            loader.loadClass("Hidden");

            // instantiate the class here and use it

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

I would like to create an instance of this Hidden class and call some public methods from it. Is it possible?

you can create instance and call method as below:

you are already using your own class loader so method loadClass("Hidden") will return Class class object referring to 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();
}

here Class.forName("Hidden"); will give Class class object referring to Your class Hidden . using this reference you can get all the fields , methods, constructors and you can use them as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM