Reflection in Java

Source: Internet
Author: User

Three ways to get class classes and some methods

 PackageCn.lianxi.reflect;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Modifier;Importjava.util.Date; Public classStudent { PublicString name= "Small white"; Private intAge=24; protectedString sex= "Male"; intmoney=180; Static{System.out.println ("This is a static code block"); }     PublicStudent () {System.out.println ("This is a constructor"); }
}classa{ Public Static voidMain (String []args) {Try{System.out.println (); //three ways to get class classes//Student.class; Class name. Classes; //new Student (). GetClass (); The name of the object. GetClass ();Class cla=class.forname ("cn.lianxi.reflect.Student");//Class.forName ("Full class name")SYSTEM.OUT.PRINTLN ("The package in which:" +cla.getpackage (). GetName ()); System.out.println ("Full class Name:" +cla.getname ()); System.out.println ("Abbreviated class Name:" +cla.getsimplename ()); //gets the access modifier for the class, with the return value int intnum =cla.getmodifiers (); //The int type can be converted to the corresponding modifier by the ToString () of the modifierSystem.out.println (modifier.tostring (num)); } Catch(ClassNotFoundException e) {e.printstacktrace (); } }}classb{ Public Static voidMain (String []args) {Try{Class CLA=class.forname ("Cn.lianxi.reflect.Student"); //field[] fields = C.getfields (); just get publicfield[] fields = Cla.getdeclaredfields ();//Get all for(inti = 0; i < fields.length; i++) {System.out.println (fields[i]); } //gets the access modifier for all properties of the default int value is 0 no corresponding string type for(inti = 0; i < fields.length; i++) {System.out.println (modifier.tostring (Fields[i].getmodifiers ())); } } Catch(ClassNotFoundException e) {e.printstacktrace (); } }}

This is the result of the Mian method running in Class A

This is the package in which the static code block is located: Cn.lianxi.reflect class Name: cn.lianxi.reflect.Student abbreviation: studentpublic

This is the result of the Mian method running in class B

This is a static code block public java.lang.String cn.lianxi.reflect.Student.nameprivate int cn.lianxi.reflect.Student.ageprotected Java.lang.String Cn.lianxi.reflect.Student.sexint cn.lianxi.reflect.Student.moneypublicprivateprotected

Creating objects

class c{    publicstaticvoid  main (String []args) {        try  {             // Student stu = new Student (); coupling            Class C = class.forname ("cn.lianxi.reflect.Student");             // relative Coupling catch (   Exception e) {            e.printstacktrace ();}}    }         

Run results

This is a static code block, which is a constructor

 To open the private properties switch for a class

classd{ Public Static voidMain (String []args) {Try{Class C= Class.forName ("Cn.lianxi.reflect.Student"); Student Stu=(Student) c.newinstance (); Field field= C.getdeclaredfield ("Age"); //Open the switch to access private propertiesField.setaccessible (true);        System.out.println (Field.get (Stu)); } Catch(Exception e) {e.printstacktrace (); }    }}

Run results

This is a static code block, which is a constructor 24

  

The private method that is added in the Student class/**     * Private method *     /Private    double getsum (double number) {        return number + ten;    }

  Accessing Object Private Methods

classe{ Public Static voidMain (String []args) {Try{Class C= Class.forName ("Cn.lianxi.reflect.Student"); Student Stu=(Student) c.newinstance (); Method Method= C.getdeclaredmethod ("Getsum",Double.class); Method.setaccessible (true); //Execution Method            Doublesum = (Double) method.invoke (Stu, 50.0);        SYSTEM.OUT.PRINTLN (sum); } Catch(Exception e) {e.printstacktrace (); }    }}

Execution Result:

This is a static code block, which is a constructor 60.0

    • Get the class of a particular class in one of the three ways Class , that is, the byte code for that class
    • Class getConstructor(Class<?>... parameterTypes) gets constructed method object of the Call object
    • Call is a method that constructs a method class Constructor newInstance(Object... initargs) new Object
    • Classthe getMethod(String name, Class<?>... parameterTypes) Fetch method object for the calling object
    • Call methods of the Method object class Method invoke(Object obj, Object... args) , call the corresponding method on the object

Reflection of an array

 

 PackageCn.lianxi.reflect;Importjava.util.Arrays; Public classArrayreflect { Public Static voidMain (string[] args) {int[] A1 =New int[]{1,2,3}; int[] A2 =New int[5]; int[] A3 =New int[2] [3]; System.out.println (A1.getclass ()= = A2.getclass ());//trueSystem.out.println (A1.getclass ());//class [ISystem.out.println (A3.getclass ());//class [[ISystem.out.println (A1.getclass (). Getsuperclass () = = A3.getclass (). Getsuperclass ());//trueSystem.out.println (A2.getclass (). Getsuperclass ());//class Java.lang.Object//The following sentence is not compiled: Error: (() Java: Non-comparable type: java.lang.class<capture#1, total? Extends int[]>
And Java.lang.class<capture#2, total? Extends Int[][]>//System.out.println (a1.getclass () = = A3.getclass ());Object []b3= A3;//through//The following sentence compilation does not pass Error: (+) Java: Incompatible type: int[] cannot be converted to java.lang.object[]//Object [] b1 = A1;String S1= "ABC"; System.out.println (arrays.aslist (A1));//[[[ Email protected]]System.out.println (Arrays.aslist (S1));//[ABC] }}

Run results

true class [iclass [ itrueclass  java.lang.object[[[email PROTECTED]][ABC] 

Configuration file Loading

    • class Loader loading read-only configuration files
Class name. Class.getclassloader (). getResourceAsStream (STR);
    • The class name, Class.getresourceasstream (str), essentially invokes the class loader. Intercept as follows (Class.java under the Java.lang package)
 Public InputStream getResourceAsStream (String name) {    = resolvename (name);     = GetClassLoader0 ();     if (cl==null) {        //  A system class.        return Classloader.getsystemresourceasstream (name);    }     return Cl.getresourceasstream (name);}

About Path STR, the wording is a little fastidious.

    • No slash, relative path:str = "config.properties";
    • Slash, from the root path of the classpath:str = "/org/iot/ui/config.properties";

In the previous compilation of Java code, some conf/ folders to be added to the dependency or labeled as the source folder, which is clearly an XML file, no Java source code. From here, I now know that is the reason to load the configuration file using reflection

Introspection (introspector) & JavaBean

JavaBean the process of reading the value of attribute x: Capitalize, complement prefix, get method.

"X"--"X"--"GetX"--"methodgetx"
    • Use your own introspection to manipulate

I don't use it at the moment, so I'm not going to put the code, only the core class

Simple implementation: Using java.beans.PropertyDescriptor classes

Troublesome implementation: Use the java.beans.Introspector class to traverse getBeanInfo The return value of the method

JavaBean must have a constructor with no parameters

    • Using the Beanutils Toolkit

      • String and Integer conversions (Contrast (propertyutils)
      • Attribute Cascade Operations
      • Operation Map

Reflection in 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.