2

My simple School class looks like this:

public class School{
   ...
   public static class Student{
       public void register(){
          ...
       }
   }

}

As you see above, the School class has a inner public static class named Student. There is a method register() defined in Student.

In my main function, I am able to load the inner static Student class by:

Class<?> studentClass = Class.forName("School$Student");

I am wondering, with the above line of code, how could I invoke the register() function in java reflection way.

0

1 Answer 1

2

If you have a valid class, then you can access and invoke its methods with:

Method register = studentClass.getDeclaredMethod("register");
register.invoke(studentClass.newInstance());
Sign up to request clarification or add additional context in comments.

4 Comments

But my Student class is a static class without an empty constructor. The "newInstance()" call will cause exception
@Mellon does it have any constructors?
@Mellon Every class has its default constructor (even nested/inner ones), unless you create separate one. Also default constructor will have same visibility as class so since Student is public class then you can have access to this constructor from anywhere.
@Mellon Based on example from your question Student doesn't have any constructors so you can use default one with studentClass.newInstance(). But in case it does have constructors you can select one of them with studentClass.getConstructor(parameterTypes) then just invoke its newInstance method with parameters you described in getConstructor like studentClass.getConstructor(int.class, String.class).newInstance(1,"abc");. This should solve your problem with lack of default constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.