43

Possible Duplicate:
Create new class from a Variable in Java

I have a string

String className = "DummyClass"

Now I want to create a class object where the class name is className That is something like

Object className = new className() // I know it's not possible.

I want to know how to do this...

Community
  • 1
  • 1
Dewsworld
  • 13,367
  • 23
  • 68
  • 104

3 Answers3

69

"Using java.lang.reflect" will answer all your questions. First fetch the Class object using Class.forName(), and then:

If I want to instantiate a class that I retrieved with forName(), I have to first ask it for a java.lang.reflect.Constructor object representing the constructor I want, and then ask that Constructor to make a new object. The method getConstructor(Class[] parameterTypes) in Class will retrieve a Constructor; I can then use that Constructor by calling its method newInstance(Object[] parameters):

Class myClass = Class.forName("MyClass");

Class[] types = {Double.TYPE, this.getClass()};
Constructor constructor = myClass.getConstructor(types);

Object[] parameters = {new Double(0), this};
Object instanceOfMyClass = constructor.newInstance(parameters);

There is a newInstance() method on Class that might seem to do what you want. Do not use it. It silently converts checked exceptions to unchecked exceptions.

Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) InvocationTargetException.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • 14
    Since java 1.5, [constructor.newInstance()](http://download.oracle.com/javase/1,5,0/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)) is varargs, so `constructor.newInstance(new Double(0), this);` will do (instead of using the cumbersome `Object[]` way). Same goes for `Class.getConstructor()` (no need for ugly Class[]) – Bohemian Sep 21 '11 at 07:20
  • What if the class is static? You wouldn't need a constructor right? – fIwJlxSzApHEZIl Feb 28 '13 at 23:14
  • 1
    @advocate, a `static` class is just an inner class that does not have an implicit reference to an instance of its containing class. It still needs to have a constructor. – Mike Samuel Mar 01 '13 at 00:49
  • Perhaps my question wasn't worded properly Mike. I didn't need to call getConstructor() for my static class whatsoever, which is what my question was getting at. Class> myClass = Class.forName(command); // get the class named after their input Method listMethod = myClass.getDeclaredMethod("list"); // get the list method from the class Object returnType = listMethod.invoke(myClass, new Object[]{}); // run the list method – fIwJlxSzApHEZIl Mar 01 '13 at 04:50
  • 1
    @advocate, if you're trying to invoke a static method, then you don't need the constructor, but you want to call invoke thus: `Object returnValue = listMethod.invoke(null, argument0, argument1, argument2);`. You pass in `null` as the value for `this` since static methods don't run in the context of an instance of the class. – Mike Samuel Mar 01 '13 at 06:08
  • What if there are no arguments? Just listMethod.invoke(null) ?? – fIwJlxSzApHEZIl Mar 01 '13 at 06:14
  • 1
    @advocate, Yes. The `invoke` method is [variadic](http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html), so you can pass any number of arguments. – Mike Samuel Mar 01 '13 at 16:01
  • Thanks Mike. This is something I've only seen before in C code and so am thus unfamiliar with it. Had no idea it was implemented in Java. – fIwJlxSzApHEZIl Mar 01 '13 at 20:51
12

You can use reflection. For example,

Object o = Class.forName(className).newInstance(); 

But className should contain full path to the class.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • 7
    Do not use `Class.newInstance`. The [javadoc](http://download.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance()) specifically says "Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The `Constructor.newInstance` method avoids this problem by wrapping any exception thrown by the constructor in a (checked) `InvocationTargetException`." – Mike Samuel Sep 21 '11 at 07:12
  • @limirus, Yeah. It's buried pretty deep in the javadoc. – Mike Samuel Sep 21 '11 at 07:16
1

Check the answer to this question: What is the difference between "Class.forName()" and "Class.forName().newInstance()"? which explains in detail how all this works.

Community
  • 1
  • 1
ivantod
  • 773
  • 3
  • 8