• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 226
  • Last Modified:

constructors

Hello,

How can I call a class constructor if I only have the class name as variable.

NOAM NA = new NOAM();

instead of using NOAM() I want to use a variable that will be the same as using NOAM() constructor.

thanks,
0
kingasa
Asked:
kingasa
1 Solution
 
mwibbelsCommented:
You mean that you have the String"NOAM" and you want to create an instance of that class? Use Class.forName() and then call newInstance() on the found class, like this:

String className = "NOAM"; // Must be full name, including package name

try {
   Class c = Class.forName(className);
   Object instance = c.newInstance();
   System.out.println(instance.getClass().getName()); // should print "NOAM"
}
catch (ClassNotFoundException e) {
   // classname not found
}
catch (InstantiationException e) {
   // classname represents an abstract class, an interface, an
  // array class, a primitive type, or void; or if the
  //  instantiation fails for some other reason
}
catch (IllegalAccessException e) {
   // the class or initializer is not accessible.
}
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now