126

I was looking as the question : Instantiate a class from its string name which describes how to instantiate a class when having its name. Is there a way to do it in Java? I will have the package name and class name and I need to be able to create an object having that particular name.

malana
  • 5,045
  • 3
  • 28
  • 41
ict1991
  • 2,060
  • 5
  • 26
  • 34
  • We *instantiate* a *class* and the result is an *object* (or: *instance*). – Andreas Dolk Mar 27 '12 at 09:09
  • 1
    The answer is yes, but I think you should ask _if_ its a good idea. With great power (reflection) comes great responsibility and you should only use it if you understand and have considered the consequences. – c1moore Dec 02 '16 at 00:19

9 Answers9

286

Two ways:

Method 1 - only for classes having a no-arg constructor

If your class has a no-arg constructor, you can get a Class object using Class.forName() and use the newInstance() method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).

For example:

Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();

Method 2

An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor object and call a newInstance() method on this object:

Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);

Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:

  • the JVM can't find or can't load your class
  • the class you're trying to instantiate doesn't have the right sort of constructors
  • the constructor itself threw an exception
  • the constructor you're trying to invoke isn't public
  • a security manager has been installed and is preventing reflection from occurring
Community
  • 1
  • 1
Simon Nickerson
  • 42,159
  • 20
  • 102
  • 127
20
MyClass myInstance = (MyClass) Class.forName("MyClass").newInstance();
amit
  • 175,853
  • 27
  • 231
  • 333
scibuff
  • 13,377
  • 2
  • 27
  • 30
  • 16
    It's worth mentioning that this doesn't work if the class has no parameterless constructor (and has other constructors), or if the parameterless constructor is inaccessible. – Dawood ibn Kareem Mar 27 '12 at 09:04
5

Using newInstance() directly is deprecated as of Java 8. You need to use Class.getDeclaredConstructor(...).newInstance(...) with the corresponding exceptions.

Carrol
  • 1,225
  • 1
  • 16
  • 29
4

To make it easier to get the fully qualified name of a class in order to create an instance using Class.forName(...), one could use the Class.getName() method. Something like:

class ObjectMaker {
    // Constructor, fields, initialization, etc...
    public Object makeObject(Class<?> clazz) {
        Object o = null;

        try {
            o = Class.forName(clazz.getName()).newInstance();
        } catch (ClassNotFoundException e) {
            // There may be other exceptions to throw here, 
            // but I'm writing this from memory.
            e.printStackTrace();
        }

        return o;
    }
}

Then you can cast the object you get back to whatever class you pass to makeObject(...):

Data d = (Data) objectMaker.makeObject(Data.class);
Roberto
  • 987
  • 1
  • 9
  • 21
3

use Class.forName("String name of class").newInstance();

Class.forName("A").newInstance();

This will cause class named A initialized.

Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
1

Use java reflection

Creating New Objects There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:

import java.lang.reflect.*;

   public class constructor2 {
      public constructor2()
      {
      }

      public constructor2(int a, int b)
      {
         System.out.println(
           "a = " + a + " b = " + b);
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("constructor2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Constructor ct 
              = cls.getConstructor(partypes);
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj = ct.newInstance(arglist);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
kornero
  • 1,109
  • 8
  • 11
1

Class.forName("ClassName") will solve your purpose.

Class class1 = Class.forName(ClassName);
Object object1 = class1.newInstance();
Ali Ben Messaoud
  • 11,690
  • 8
  • 54
  • 87
Balaswamy Vaddeman
  • 8,360
  • 3
  • 30
  • 40
0
String str = (String)Class.forName("java.lang.String").newInstance();
Chen Harel
  • 9,684
  • 5
  • 44
  • 58
0

something like this should work...

String name = "Test2";//Name of the class
        Class myClass = Class.forName(name);
        Object o = myClass.newInstance();
Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54