Last updated 2004-06-28 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java Glossary : C words : Class.forName.
You can't instantiate Class objects, but most the Class methods are instance methods, not static. So how do you get a Class object:
Class cDog = Dog.class; // Dog class object. Class cDog2 = dog.getClass(); // actual class of dog object, not class of dog reference. Class cCurrent = this.getClass(); // current class. Class cDog3 = Class.forName( "Dog" ) // Dog class from class name. Class cDog4 = Class.forName( "com.mindprod.dogs.Dog" ) // Dog class from package name. Class cString = java.lang.String.class; // gets String class Class cStringArray = String[].class; // gets String array class Class cdouble = double.class; // gets pseudoclass representing double primitive. Class cDouble = Double.class; // gets Double wrapper class Class cdouble2 = Double.TYPE; // gets underlying double primitive.
You can then use methods like Class.toString, Class.getName, Class.getLoader and Class.getSuperclass to tell you even more about the class. Once you have the class, you can then play games with java.lang.reflect.*. Given just the class object, you can find out the constructors, methods, parameters to those methods and the members. You can also dynamically construct new objects and calls to methods on those objects.
To keep thing simple, when you have variable classes, they all implement some interface, abstract class or base class, in this case HolInfo:
// variable fully qualified class name String classname = "com.mindprod.Holidays.Christmas"; // Create a class Christmas object, with an interface HolInfo reference HolInfo holidayDelegate = ( HolInfo ) ( Class.forName ( classname ).newInstance() ); // Execute methods of the Christmas object. String rule = holidayDelegate.getRule();
To go the other way use obj.getClass().getName().
For a practical example of the technique,
Here is how you find out where a class file came from on disk or on the net.
// Find out where the source code for for some class came from CodeSource source = SomeClass.getProtectionDomain().getCodeSource(); if ( source != null ) { URL location = source.getLocation(); ... }
It may not have location, e.g. it was dynamically generated on the fly.
home |
Canadian Mind Products | |||
| mindprod.com IP:[24.87.56.253] | ||||
| Your IP:[80.134.30.163] | ||||
| You are visitor number 8978. | ||||
| Please send errors, omissions and suggestions | ||||
| to improve this page to Roedy Green. | ||||
| You can get a fresh copy of this page from: | or possibly from your local J: drive mirror: | |||
| http://mindprod.com/jgloss/classforname.html | J:\mindprod\jgloss\classforname.html | |||