Switch to full style
General Java code examples
Post a reply

Create object instance from class Name by reflection

Tue Apr 23, 2013 9:30 pm

Create object instance from class Name by reflection
java code
public static Object constructObject(String className) {

Object[] params = { className };

Object result = null;
if (className != null)
className = className.trim();

try {

Class refClass = Class.forName(className);

result = refClass.newInstance();

} catch (ClassNotFoundException exception) {
// Do Something

} catch (IllegalAccessException exception) {
// Do Something

} catch (InstantiationException exception) {
// Do Something
}

return result;
}


Use class constructor
java code
Constructor argsConstructor = refClass 
.getConstructor(argsClass);
// send the needed parameters for constructor if there are ?
result = argsConstructor.newInstance(constructorParams);




Post a reply
  Related Posts  to : Create object instance from class Name by reflection
 create Logo Reflection     -  
 What exact mean by Object, Reference and Instance?     -  
 A clone instance of class in php     -  
 Pass class instance as parameter in php     -  
 Create Object and get its type     -  
 create a named query within entity class     -  
 Define class helper class to check the method existance     -  
 java abstract class,concrete class and interface     -  
 relationship between the Canvas class and the Graphics class     -  
 Define class inside another class C++     -  

Topic Tags

Java Methods