The reflection mechanism of Java

Source: Internet
Author: User

1. Overview

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 and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.

2. Reflections on the mechanism of reflection

First we do the preparatory work:

 PackageCom.myreflex; Public classDemo {PrivateString str1;  PublicString str2; Private voidfun1 () {System.out.println ("Call Fun1"); }     Public voidfun2 () {System.out.println ("Call Fun2"); }         Public voidFUN3 (intparam1, String param2) {System.out.println ("Fun3 with param:" +param1+ "and" +param2); }         PublicDemo (intparam1, String param2) {System.out.println ("Consturctor with" +param1+ "," +param2); }         PublicDemo () {System.out.println ("Consturctor with no param"); }}

Let's start by creating a test class that contains a private property, a public property, a private method, and a public method. and three different parametric construction methods are prepared for this class. We'll use this class later.

(1) Get the full package name and class name from an object
 Package Com.myreflex;  Public class Testmain {        publicstaticvoid  main (string[] args) {        new  Demo ();         // get the full package name and class name from an object         System.out.println (Demo.getclass (). GetName ());     }    }

The result is: Com.myreflex.Demo.

(2) instantiation of a class
 PackageCom.myreflex; Public classTestmain { Public Static voidMain (string[] args) {Class<?>Clazz; Demo Demo=NULL; Try{clazz= Class.forName ("Com.myreflex.Demo"); Demo= (Demo) clazz.newinstance ();//using Clazz.newinstance () to instantiate the demo}Catch(Instantiationexception e) {}Catch(Illegalaccessexception e) {}Catch(ClassNotFoundException E1) {} demo.fun2 (); }    }

Printing results are:

Consturctor with no paramyou call fun2

Note, however, that this method requires the demo to have a default constructor with no parameters.

(4) Get the properties of a class
 PackageCom.myreflex;ImportJava.lang.reflect.Field; Public classTestmain { Public Static voidMain (string[] args) {Class<?>Clazz; Try{clazz= Class.forName ("Com.myreflex.Demo");            field[] fields; fields= Clazz.getfields ();//get all properties of a class (public)System.out.println ("--------------getfields----------------");  for(Field field:fields) {System.out.println (Field.gettype (). GetName ());            System.out.println (Field.getname ()); } Fields= Clazz.getdeclaredfields ();//get all properties of the class (public and private)System.out.println ("--------------getdeclaredfields----------------");  for(Field field:fields) {System.out.println (Field.gettype (). GetName ());            System.out.println (Field.getname ()); }        } Catch(Exception e) {} }}

Printing results are:

--------------getfields----------------java.lang.Stringstr2-------------- Getdeclaredfields----------------java.lang.Stringstr1java.lang.Stringstr2
(4) Methods of obtaining classes
 PackageCom.myreflex;ImportJava.lang.reflect.Method; Public classTestmain { Public Static voidMain (string[] args) {Class<?>Clazz; Try{clazz= Class.forName ("Com.myreflex.Demo");            Method[] methods; Methods= Clazz.getmethods (); System.out.println ("--------------getmethods----------------");  for(Method method:methods) {System.out.println (Method.getname ()); } Methods= Clazz.getdeclaredmethods (); System.out.println ("--------------getdeclaredmethods----------------");  for(Method method:methods) {System.out.println (Method.getname ()); }        } Catch(Exception e) {} }}

Printing results are:

--------------GetMethods----------------fun2fun3waitwaitwaitequalstostringhashcodegetclassnotifynotifyall --------------getdeclaredmethods----------------fun1fun2fun3
(5) Get the parameter type of the method
 PackageCom.myreflex;ImportJava.lang.reflect.Method; Public classTestmain { Public Static voidMain (string[] args) {Class<?>Clazz; Try{clazz= Class.forName ("Com.myreflex.Demo"); Method[] Methods=Clazz.getdeclaredmethods ();  for(Method method:methods) {System.out.println (Method.getname ()+ "The parameter types of the method are:"); Class<?>[] Paramclasses =method.getparametertypes ();  for(class<?>paramclass:paramclasses)                {System.out.println (Paramclass.getname ()); }            }        } Catch(Exception e) {} }}

Printing results are:

The parameter types of the Fun1 method are: The parameter types of the Fun2 method are: The parameter types of the Fun3 method are: int java.lang.String
(6) Invocation of a class method:
 PackageCom.myreflex;ImportJava.lang.reflect.Method; Public classTestmain { Public Static voidMain (string[] args) {Class<?>Clazz; Try{clazz= Class.forName ("Com.myreflex.Demo"); Method method2= Clazz.getdeclaredmethod ("fun2");//ways to get fun2Method method3 = Clazz.getdeclaredmethod ("Fun3",int.class, String.class);//ways to get Fun3Demo demo = (demo) clazz.newinstance ();//Create an instance of demoMethod2.invoke (demo);//Executive Fun2Method3.invoke (demo, 111, "AAA");//Executive Fun3}Catch(Exception e) {} }}
(7) Get parent class
 package   Com.myreflex;  public  class   Testmain { static  void   main (string[] args) {class<        /span><?> Clazz;  try   {Clazz  = Class.forName ("C            Om.myreflex.Demo ");            Clazz  = Clazz.getsuperclass ();        System.out.println (Clazz.getname ());  catch   (Exception e) {}}}  

The result is: Java.lang.Object.

(8) Get all constructors
 PackageCom.myreflex;ImportJava.lang.reflect.Constructor; Public classTestmain { Public Static voidMain (string[] args) {Class<?>Clazz; Try{clazz= Class.forName ("Com.myreflex.Demo"); Constructor<?>[] Cons =clazz.getconstructors ();  for(constructor<?>constructor:cons)            {System.out.println (constructor); }        } Catch(Exception e) {} }}

Printing results are:

 Public Com.myreflex.Demo ()  public Com.myreflex.Demo (int, java.lang.String)
(9) To be continued

.....................

The reflection mechanism of Java

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.