How do I use getConstructor(params).newInstance(args)?

后端 未结 3 1688
谎友^
谎友^ 2021-02-02 09:10

This could well be a stupid question, but I\'m new to Java, so...

I\'ve currently got some code where currently this is being used clazz.asSubclass(asSubclassOfCla

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-02 09:40

    In Java this is called Reflection.

    Assuming the class has this constructor, otherwise you will get a NoSuchMethod exception I believe.

    clazz.asSubclass(asSubclassOfClass)
        .getConstructor(String.class,XYZ.class)
        .newInstance("howdy",XyzObj);
    

    Since you are new to Java, let me give you an easier so that you can understand what's going on under the hood when you do this.

    Assume you have the following class:

    public class ParentClazz{
            String someVar;
        public ParentClazz(){
            someVar="test";
        }
        public ParentClazz(String someVar){
            System.out.println("I have been invoked");
            this.someVar=someVar;
        }
    }
    

    Then you have the following main method:

    public static void main(String[] args) throws ParseException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
               ParentClazz.class.asSubclass(ParentClazz.class).getConstructor(String.class).newInstance("howdy");
        }
    

    If you run this you will notice the console output print message - I have been invoked. This means that using reflection you have invoked the constructor of ParentClazz.

    You can do the same thing if the scenario allows you is by using standard object creation process:

    ParentClazz clazz = new ParentClazz("howdy");
    

    Hope this helps you understand it.

提交回复
热议问题