Understanding and application of Java reflection Class

Source: Internet
Author: User

The main parsing classes in this article are:

Classlodaer,class,field,method,constructor.

The objective of this article is simple, simply to explain these commonly used reflection classes. The common methods in these classes are described.

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language.
The Java Reflection mechanism provides the following functions: To determine the class to which any object belongs at run time, to construct an object of any class at run time, to determine the member variables and methods that any class has at run time, to invoke a method of any object at run time, and to generate a dynamic proxy.

Class:

 Public Final class extends Object implements Serializable, Genericdeclaration, Type, annotatedelement

The class declaration indicates that class is an end class, is an object, and can be serialized.

Class has no public constructor method. Classobjects are constructed automatically by the Java virtual machine and by calling methods in the class loader when the class is loaded defineClass .

The following example uses Class an object to display the class name of an object: (using Object.getclass ())

Object obj=New  object ();        System.out.println (Obj.getclass (). GetName ());

Notice here the GetClass () method:

Public final native class<?> GetClass ();

A local method was called to get the class of the classes.

The difference between the class keyword and the GetClass ().

Public  Class Animal{}public class Dog extends Animal {public static void main (string[] args) {Animal Animal       = new Dog ();       System.out.println ("GetClass ():  " +animal.getclass (). GetName ());    System.out.println ("Class:  " +animal.class.getname ()); }} output GetClass ():  com.abc.Dogclass:  com.abc.Animal

Because the method of Object.getclass () exists, any object in memory can have its own type. The reflection is done by parsing the byte-code file.

Reflection method: Forname ()

@CallerSensitive public    static class<?> forname (String className)                throws ClassNotFoundException {        class<?> caller = Reflection.getcallerclass ();        Return FORNAME0 (ClassName, True, Classloader.getclassloader (caller), caller);    }

This is the most commonly used method of reflection. For a byte code file name to parse, get class. As you can see, forname () is also involved in parsing the class loader.

What is ClassLoader? What's the effect?

As you all know, a Java program is organized by several. class files. When the program is running, it calls an entry function of the program to invoke the relevant functions of the system, which are encapsulated in different class files, so often from this class file to invoke another class file in the method, if another file does not exist, A system exception is thrown. when the program starts, it does not load all the class files that the program will use at once, but it dynamically loads a class file into memory according to the needs of the program through the Java class loading mechanism (ClassLoader). As a result, only the class file is loaded into memory before it can be referenced by another class. so ClassLoader is used to dynamically load class files into memory.

The methods and construction methods of objects created by the ClassLoader can reference other classes. To determine the referenced class, the Java virtual machine calls the method that originally created the class loader for the class loadClass .

For example, an application can create a network class loader to download class files from the server. The sample code looks like this:

   ClassLoader loader = new Networkclassloader (host, port);   Object main = Loader.loadclass ("main", true). Newinstance ();

(ClassLoader of the relevant knowledge points, not in this article to comb.) )

Class.forName (String className);

Examples of valid class names include: (Package.classname)

   "Java.lang.String" "Javax.swing.jspinner$defaulteditor" "   java.security.keystore$builder$filebuilder$1"   "Java.net.urlclassloader$3$1"

Class.forName (String ClassName) needs to throw an exception: ClassNotFoundException.

Class clazz=class.forname ("Testreflect.atest"); System.out.println (Clazz.getclass (). GetName ()); System.out.println (Clazz.getclassloader ()); Object obj=clazz.newinstance (); System.out.println ("This object is" +obj.getclass (). GetName ()); output Java.lang.class[email protected] This object is Testreflect.atest

The following classes are introduced by code

The class to be used for reflection

Package Testreflect;public class Atest {private int field1=1;public String field2= "field2";p rivate int method1 () {return 1 ;} public string Method2 (string a) {return "METHOD2";} Public atest () {}public atest (int b) {}}

  

Test class

Package Testreflect;import java.lang.reflect.*;p ublic class Main {public static void main (string[] args) {try {class Clazz =class.forname ("Testreflect.atest"); System.out.println (Clazz.getclass (). GetName ()); System.out.println (Clazz.getclassloader ()); Object obj=clazz.newinstance (); System.out.println ("This object is" +obj.getclass (). GetName ()); The method for obtaining field in/** * class is * 1.getDeclaredField ("field1"); * 2.getDeclaredFields (); Returns an array of field objects that reflect all the fields declared by the class or interface represented by this class * object. Includes public, protected, default (package) access, and private fields, but does not include inherited fields. * 3.getFields (); * 4.getFields ("Field2"); * * * * * */field Field1=clazz.getdeclaredfield ("field1"); Field1.setaccessible (true); System.out.println (field1); System.out.println (Field1.getname () + ":" +field1.get (obj)); Field[] Fields1=clazz.getfields (); Field[] Fields2=clazz.getdeclaredfields (); System.out.println (fields1.length); System.out.println (fields2.length); Method Method1=clazz.getdeclaredmethod ("method1", null); Method1.setaccessible (true); System.out.println (method1); Object Value1=method1.invoke (obJ, NULL); System.out.println ("The value returned by METHOD1 is" +value1); Method Method2=clazz.getdeclaredmethod ("Method2", String.class); System.out.println (METHOD2); System.out.println (Method2.getparametertypes (). length); SYSTEM.OUT.PRINTLN ("Method2 Returns a value of" +method2.invoke (obj, "1")); Method[] Methods1=clazz.getdeclaredmethods ()///Return method array, the order of the methods is not determined for (int i=0;i<methods1.length;i++) { System.out.println (Methods1[i]), if ("Method2". Equals (Methods1[i].getname ())) System.out.println ("parameter list of METHOD2" + Methods1[i].getparametertypes ());} Constructor cons1=clazz.getdeclaredconstructor (NULL); Constructor Cons2=clazz.getdeclaredconstructor (Int.class); System.out.println (CONS1); System.out.println (CONS2); Object o1=cons2.newinstance (1); System.out.println (O1.getclass ());} catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Instantiationexception e) {//TODO auto The Catch block E.printstacktrace (); catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Nosuchfieldexception e) {//TODO automatically generated catch block E.printstacktrace ();} catch (SecurityException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (Nosuchmethodexception e) {//TODO auto-generated cat CH Block e.printstacktrace ();} catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace ();} catch (InvocationTargetException e) {//TOD O Auto-generated catch block E.printstacktrace ();}}}




Output Result:
Java.lang.Class
[Email protected]
This object is Testreflect.atest
private int TestReflect.ATest.field1
Field1:1
1
2
private int testReflect.ATest.method1 ()
The value returned by METHOD1 is 1
Public java.lang.String testReflect.ATest.method2 (java.lang.String)
1
The value returned by METHOD2 is METHOD2
private int testReflect.ATest.method1 ()
Public java.lang.String testReflect.ATest.method2 (java.lang.String)
METHOD2 List of parameters [ljava.lang.class;@52e922
Public Testreflect.atest ()
public testreflect.atest (int)
Class Testreflect.atest

The purpose of this article is not to explain. So you can also directly take the code to do the test.

Above.

Understanding and application of Java reflection Class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.