We can learn the exact type of an object through Java's rtti mechanism, but this requires a prerequisite: the type must be known at compile time so that Rtti can recognize it, that is, at compile time, the compiler must know the class handled by Rtti. The question comes, what if we can't get the actual class to which the object belongs? For example, we get a string of bytes from a disk file or network and are told that these bytes represent a class, how can we use such a class? The solution is to use the Java reflection mechanism to understand the literal meaning that we can map the object to the class to which it belongs, thus obtaining information about the corresponding class, which is reflection. In the Rtti section of the Java type information, we have used the reflection mechanism to obtain the method information of the class that the object belongs to, the class class and the Java.lang.reflect class library have supported the reflection mechanism, and by querying the Java.lang.reflect class library, Let's take a first example:
1 Packagere;2 ImportJava.util.*;3 Importjava.lang.reflect.*;4 Public classreflect{5 Public Static voidMain (string[] args)throwsexception{6Class som=class.forname ("Re. Some ");7Field[] Fields=som.getdeclaredfields ();8Constructor[] Ctors=som.getconstructors ();9Method[] Methods=som.getmethods ();TenPrint ("Fields of Some"); One for(Field field:fields) { APrint ("" +field); - } -Print ("Methods of some"); the for(Method method:methods) { -Print ("" +method.tostring ()); - } -Print ("Constructors of some"); + for(Constructor cto:ctors) { -Print ("" +cto.tostring ()); + } A } at Static voidprint (Object o) { - System.out.println (o); - } - } - classsome{ - Private intVal=0; in PrivateString str=NULL; - PublicSome () { to + } - Public voidsetString (String str) { the This. str=str; * } $ Public voidSetval (intval) {Panax Notoginseng This. val=Val; - } the PublicString getString () { + returnstr; A } the Public intGetval () { + returnVal; - } $}View Code
By running the results, we get the member variables, member methods and construction methods of the some class, where the results generated by Class.forName () are not known at compile time, and all method signature information is extracted at runtime, so although sometimes we may not be able to get a class, But as soon as we get the object of this class, we can still get most of the information for the class that created the object, which is reflection, which reflects the class information that created the object through the object information at run time.
The above is the "thinking in Java" Learning summary, good night, sleep ...
Java Reflection mechanism