Smajl
Smajl

Reputation: 7995

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?

Upvotes: 1

Views: 2222

Answers (1)

Prashant
Prashant

Reputation: 2614

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.

Upvotes: 4

Related Questions