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

后端 未结 3 1689
谎友^
谎友^ 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:35
    clazz.asSubclass(asSubclassOfClass)
         .getConstructor(String.class, XYZ.class)
         .newInstance("howdy", XyzObj)
    

    Which assumes that the constructor args are in the specified order

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-02 10:00

    Here is an example of creating classes without the new keyword. The classes take other classes both primitives and Objects as their parameters. The example also shows the instance of a subclass and a Parent class being created

    public class ConstructorInstantiateWithoutNew 
    {
        @SuppressWarnings("rawtypes")
        public static void main( String [] args )
        {
            Class<Drinker> clazz_drinker = Drinker.class;
            Class [] paramTypes = { Fizz.class, Colour.class, int.class };
            Object [] paramValues = {  new Fizz(), new Colour(), new Integer(10) };
    
            Class<Drunk> clazz_drunk = Drunk.class;
            Class [] paramTypesSub = { Fizz.class, Colour.class, int.class, boolean.class };
            Object [] paramValuesSub = {  new Fizz(), new Colour(), new Integer(10), true };
    
            try 
            {
                Drinker drinker = clazz_drinker.getConstructor( paramTypes ).newInstance( paramValues );
                drinker.drink();
    
                Drunk drunk = clazz_drunk.getConstructor(paramTypesSub).newInstance(paramValuesSub);
                drunk.drink();
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            } 
        }
    }
    
    class Drinker
    {
        int n;
    
        public Drinker( Fizz f, Colour c, int n)
        {
            this.n = n;
        }
    
        public void drink()
        {
            System.out.println( "Dad drank " + (n*10) + " ml");
        }
    }
    
    class Drunk extends Drinker
    {
        boolean trouble;
        public Drunk(Fizz f, Colour c, int n, boolean inDogHouse)
        {
            super(f,c,n);
            trouble = inDogHouse;
        }
    
        public void drink()
        {
            System.out.println( 
                    "Dad is Grounded: " + trouble + 
                    " as he drank over "+ 
                    (n*10) + " ml");
        }
    }
    
    class Fizz {} class Colour {}
    

    Hope this is useful

    Kind regards

    Naresh Maharaj

    0 讨论(0)
提交回复
热议问题