Java Reflection mechanism

Source: Internet
Author: User

Reflection, in short I literally did not see what the meaning. Individuals think that the "reflection" name is not good enough, it should be called the Java selection mechanism

Just like the jquery selector, you can get all the information from the DOM node during the run.

The same is true of the Java reflection mechanism, which means that all the method properties of any class can be obtained and invoked during the execution of a program.


Packages that specialize in reflection are already available in Java java.lang.reflect

Let's talk about class objects.

Example 1: Three Methods for class object creation

Loadclass.java

Package Com.zero;public class LoadClass {public static void main (String [] args) throws classnotfoundexception {* * * class object creation Three methods (class object is an instance of Class) */class T1 = null; Class t2 = null; Class T3 = null;t1 = Class.forName ("Com.zero.Test"), t2 = new Test (). GetClass (); t3 = Test.class;}} Class Test {//Static statement block, class load run, run only once Static{system.out.println ("class loading");}}

Example 1 run Result: in class loading

The method used to create the above class objects is the most commonly used method of class.forname ("XXX"), which is the general JDBC Connection database loaded by the JDBC driver.

Go to the point, the following case

Example 2:java reflection mechanism

Reflecttest.java

Package Com.zero;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.lang.reflect.modifier;public class Reflecttest {public static void main (String [] args) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException {Class test2 = Class.forName ("Com.zero.TestReflect");//class object creation Testreflect TT = (testreflect) Test2.newinstance ();//Instantiate Testreflect object method [] methods = Test2.getmethods ();//Get Class object member method System.out.println ("------ ---class member method is as follows-------------"); for (method m:methods) {int mo = m.getmodifiers ();//Gets the method modifier, which gets the int type, Need to use modifier.tostring () to convert System.out.print (modifier.tostring (MO) + ""); System.out.print (M.getreturntype (). GetName () + "");//method sends return type System.out.print (M.getname ());//Method name class [] Parameters = M.getparametertypes ();//all parameter types of the method System.out.print ("("); int i = 0;for (Class parameter:parameters) {System.out.print (Parameter.getname () + "" + "arg" + i++if (I < parameters.length) {System.out.print (",");}} System.out.println (") {}");} System.out.println ("---------class member variables are as follows-------------"); field[] fie = Test2.getdeclaredfields (); for (Field ff:fie) {int dd = ff.getmodifiers ();//variable modifier System.out.print (Modifier . toString (DD) + ""); System.out.print (Ff.gettype (). GetName () + "");//variable Type SYSTEM.OUT.PRINTLN (Ff.getname ());//variable name}SYSTEM.OUT.PRINTLN ("- --------Printparameter () method call-------------"), for (method M:methods) {if (M.getname (). Equals (" Printparameter ")) {// Method called method name Printparameter string re = (string) m.invoke (TT);//Execute Method System.out.println ("method returned:" + Re);}}} Class Testreflect {static{system.out.println ("------------in---------class loading");} Member variable private int a;private String b;private float c;public void init () {THIS.A = 100;this.b = "China"; this.c = 0.77f;} public void Printparameter () {init (); System.out.println ("a=" + A + "b=" + B + "c =" + C);} Public String Ex () {this.b = "Chinese"; System.out.println (b); return this.b;}}

Operation Result:

---------class Load---------------------class member methods are as follows-------------public void Init () {}public java.lang.String ex () {}public void Printparameter () {}public final void wait () {}public final void wait (long arg0, int arg1) {}public final native void Wait (lon G arg0) {}public native int hashcode () {}public final native Java.lang.Class getclass () {}public Boolean equals ( Java.lang.Object arg0) {}public java.lang.String toString () {}public final native void Notify () {}public final native void n Otifyall () {}---------class member variables are-------------private int aprivate java.lang.String bprivate float C---------Printparameter () method call-------------a=100 B=china c = 0.77 method returns: null

As can be seen in Example 2, Java can get all the information of the class according to the name of the class and can also call any method in the class (of course, I only write one-sided case, such as get the interface of the implementation of the class, throw the exception, etc. are possible, this oneself to see the API document can be)-- In fact, this is the reflection mechanism of Java ^_^

Note: In a class, a method, a method type, a member variable type, a name, and so on are all an object

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Reflection mechanism

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.