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

后端 未结 3 1701
谎友^
谎友^ 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 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 clazz_drinker = Drinker.class;
            Class [] paramTypes = { Fizz.class, Colour.class, int.class };
            Object [] paramValues = {  new Fizz(), new Colour(), new Integer(10) };
    
            Class 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

提交回复
热议问题