Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(asSubclassOfClass).getConstructor().newInstance()

I need to pass some arguments to the contructort so I want to change it to: clazz.asSubclass(asSubclassOfClass).getConstructor(params).newInstance(args)

What I don't understand is what I need to pass in as params and what I need to pass in as args.

Let's say I wanted to pass in a String "howdy" and some object of type XYZ called XyzObj in. How would I specify that? WHat would I pass as params and what would I pass as args?

like image 451
Eli Avatar asked Feb 17 '12 21:02

Eli


2 Answers

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.

like image 65
CoolBeans Avatar answered Oct 05 '22 03:10

CoolBeans


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

like image 21
Naresh Maharaj Avatar answered Oct 05 '22 01:10

Naresh Maharaj