How to create a class instance by using class name in Java?
The Class.forName() method allows you to map a case-sensitive class name to the Class instance representing gaven class. Then you can invoke its newInstance() to create an instance of that class. For Example:
Class tc = Class.forName("com.xyzws.common.Type");
Tyep myType = tc.newInstance();
In the event that the Class could not be found, resolved, verified, or loaded, Class.forName
throws one of several different Exceptions, all of which are listed in the javadoc page for
java.lang.Class.
Another example to check where class's jar file is:
try {
String qualifiedClassName="org.xbill.DNS.DSRecord";
Class qc = Class.forName(qualifiedClassName);
CodeSource source = qc.getProtectionDomain().getCodeSource();
if ( source != null ) {
URL location = source.getLocation();
System.out.println( qualifiedClassName + " : " + location );
}
else {
System.out.println( qualifiedClassName + " : "
+ "unknown source, likely rt.jar" );
}
}
catch ( Exception e ) {
System.err.println( "Unable to locate class on command line." );
e.printStackTrace();
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?