Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a class with Class.forName() and which have a constructor which takes arguments

I am instantiating a class like this.

myObj = (myObj) Class.forName("fully qualified class name here").newInstance(); 

My doubt here is if we have a constructor which takes arguments how can we instantiate it like above one.

Thanks,
Narendra

like image 297
Narendra Avatar asked Apr 14 '11 03:04

Narendra


People also ask

What the class forName () does?

forName. Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName ) this method attempts to locate, load, and link the class or interface.

How do you initialize a constructor?

There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.

Is constructor used for initialization?

A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.

How do you create a class object from a constructor in Java?

Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.


2 Answers

Use Class.getConstructor() and call Constructor.newInstance() on that. For example if this is your constructor on class Foo:

public Foo(String bar, int baz) { } 

You'd have to do something like this:

Constructor c = Class.forName("Foo").getConstructor(String.class, Integer.TYPE); Foo foo = (Foo) c.newInstance("example", 34); 

You'll have to know what arguments need to be passed to the constructor. If that's not desirable you should consider having an empty constructor. Then have methods to set what you'd normally pass into the constructor.

One might ask if you have the right pattern here though. Do you really need to use reflection, perhaps there's a better approach? If you know you're going to be casting to your object already, why not just construct it normally? You might want to provide more context as to why you need to do this. There are valid reasons, however you haven't stated any.

like image 78
WhiteFang34 Avatar answered Sep 18 '22 20:09

WhiteFang34


newInstance() always invokes default constructor.

if you want to invoke parametrized constructor,

  1. You have to get Constructor with parameter types by passing Class[] for getDeclaredConstructor method of Class
  2. You have to create constructor instance by passing Object[] for
    newInstance() method of Constructor

Have a look at example code.

import java.lang.reflect.*;  class NewInstanceDemo{     public NewInstanceDemo(){         System.out.println("Default constructor");     }     public NewInstanceDemo(int a, long b){         System.out.println("Two parameter constructor : int,long => "+a+":"+b);     }     public NewInstanceDemo( int a, long b, String c){         System.out.println("Three parameter constructor : int,long,String => "+a+":"+b+":"+c);     }     public static void main(String args[]) throws Exception {          NewInstanceDemo object = (NewInstanceDemo)Class.forName("NewInstanceDemo").newInstance();         Constructor constructor1 = NewInstanceDemo.class.getDeclaredConstructor( new Class[] {int.class, long.class});         NewInstanceDemo object1 = (NewInstanceDemo)constructor1.newInstance(new Object[]{1,2});      } } 

output:

java NewInstanceDemo Default constructor Two parameter constructor : int,long => 1:2 

Have a look at oracle documentation page for more details.

like image 23
Ravindra babu Avatar answered Sep 19 '22 20:09

Ravindra babu