Java Reference
In-Depth Information
// Express a class literal as a type name followed by ".class"
c = int . class ; // Same as Integer.TYPE
c = String . class ; // Same as "a string".getClass()
c = byte []. class ; // Type of byte arrays
For primitive types and void , we also have class objects that are represented as literÔÇÉ
als:
// Obtain a Class object for primitive types with various
// predefined constants
c = Void . TYPE ; // The special "no-return-value" type
c = Byte . TYPE ; // Class object that represents a byte
c = Integer . TYPE ; // Class object that represents an int
c = Double . TYPE ; // etc; see also Short, Character, Long, Float
For unknown types, we will have to use more sophisticated methods.
Class Objects and Metadata
The class objects contain metadata about the given type. This includes the methods,
fields, constructors, etc. that are defined on the class in question. This metadata can
be accessed by the programmer to investigate the class, even if nothing is known
about the class when it is loaded.
For example, we can find all the deprecated methods in the class file (they will be
marked with the @Deprecated annotation):
Class <?> clz = getClassFromDisk ();
for ( Method m : clz . getMethods ()) {
for ( Annotation a : m . getAnnotations ()) {
if ( a . annotationType () == Deprecated . class ) {
System . out . println ( m . getName ());
}
}
}
We could also find the common ancestor class of a pair of class files. This simple
form will work when both classes have been loaded by the same classloader:
public static Class <?> commonAncestor ( Class <?> cl1 , Class <?> cl2 ) {
if ( cl1 == null || cl2 == null ) return null ;
if ( cl1 . equals ( cl2 )) return cl1 ;
if ( cl1 . isPrimitive () || cl2 . isPrimitive ()) return null ;
List < Class <?>> ancestors = new ArrayList <>();
Class <?> c = cl1 ;
while (! c . equals ( Object . class )) {
if ( c . equals ( cl2 )) return c ;
ancestors . add ( c );
c = c . getSuperclass ();
}
c = cl2 ;
while (! c . equals ( Object . class )) {
Search WWH ::




Custom Search