Reflection (1), reflection (

Source: Internet
Author: User

Reflection (1), reflection (
I. Use of Class classes

1. The reflection mechanism of Java is to load, probe, and self-audit only when the program is running. Use a class that is unknown during the compilation period. This feature is reflection.

2. In the object-oriented world, everything is an object (except for static members, the common data type is not an object), the Class is an object Class, And the Instance Object of java. lang. Class
3. How to represent the Class instance

Public class ClassDemo1 {public static void main (String [] args) {// create the Foo class instance object foo1 Foo foo1 = new Foo (); // any Class is an instance object of Class, and these objects are created by JVM, this instance object has three Representation Methods // the first one --> actually, it tells us that any class has an implicit static member variable Class c1 = Foo. class; // The second representation --> you know that the object of this Class gets class c2 = foo1.getClass () through the getClass method;/* Official Website: c1, c2 indicates the class type of the Foo Class * class type: the Class is also an object and is an instance object of the class, this object is the Class type of the Class ** // a Class can only be an object of the Class System. out. println (c1 = c2); // The third expression --> use Class. forName () Class c3 = null; try {c3 = Class. forName ("JavaSE. reflect. foo ");} catch (ClassNotFoundException e) {e. printStackTrace ();} System. out. println (c2 = c3);/** you can create an object instance of the class through the class type of the class --> through c1, c2, when c3 creates the Foo Instance Object **/try {// when calling newInstance (), there must be no parameter constructor: Foo foo2 = (Foo) c1.newInstance (); Foo foo3 = (Foo) c2.newInstance (); Foo foo4 = (Foo) c3.newInstance (); foo2.print (); foo3.print (); foo4.print ();} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace () ;}} class Foo {void print () {System. out. println ("I am method print in Foo ");}}

4. Class. forName () not only indicates the Class type, but also indicates the dynamic loading Class
The load class at compile time is a static load class, and the load class at run time is a dynamic load class.

ClassDemo2:

Public class ClassDemo2 {public static void main (String [] args) {/** at this time, an error is reported during running. The C1 class, C1 start (), and C2 class cannot be found, start () * of C2. However, if we only want to call the C1 method and add the C1 class and its method, the program will still report an error because C2 and its method cannot be found, the new object is a static loading class, and all possible classes need to be loaded at the time of compilation * this problem can be solved through dynamic loading class **/if ("C1 ". equals (args [0]) {C1 c1 = new C1 (); c1.start ();} if ("C2 ". equals (args [0]) {C2 c2 = new C2 (); c2.start ();}}}

ClassDemo3:

Public class ClassDemo3 {public static void main (String [] args) {try {// dynamic loading Class, Class c = class at runtime. forName (args [0]); // creates CAble cc = (CAble) c. newInstance (); cc. start ();} catch (Exception e) {e. printStackTrace ();}}}

CAble:

public interface CAble {    void start();}

C1:

public class C1 implements CAble{    public void start() {        System.out.println("C1 start run...");    }}

C2:

public class C2 implements CAble {    public void start() {        System.out.println("C2 start run...");    }}

5. Basic Data Types
The void keyword also has a class type.

Public class ClassDemo4 {public static void main (String [] args) {Class c1 = int. class; // int class type System. out. println (c1); Class c2 = String. class; // String Class type class c3 = double. class; Class c4 = Double. class; System. out. println (c3 = c4); Class c5 = void. class; System. out. println (c5); Class c6 = C1.class; System. out. println (c6.getName (); System. out. println (c6.getSimpleName ());}}
Ii. Method reflection
ClassUtil:
/*** Print the class information, including the member function ** @ param obj */public static void printClassMethodMessage (Object obj) {// 1. obtains Class c = obj of a Class. getClass (); // specifies the object of the subclass to be passed, and c indicates the class type of the subclass. // 2. obtain the class name System. out. println ("Class Name:" + c. getName (); // 3. obtain the class Method/*** Method class. The class type of the Method * a member Method is a Method object. The * getMethods () Method obtains all public functions, including the parent class inherited * getDeclaredMethods () gets all the methods declared by the class itself, without asking for access permissions */Method [] MS = c. getMethods (); for (int I = 0; I <ms. length; I ++) {// obtain the Class type of the return value type Class returnType = MS [I]. getReturnType (); System. out. print (returnType. getName () + ""); // obtain the method name System. out. print (MS [I]. getName () + "("); // get the parameter type --> get the type of the parameter list Class type Class [] paramTypes = MS [I]. getParameterTypes (); for (Class class1: paramTypes) {System. out. print (class1.getName () + ",");} System. out. print (")"); System. out. println ();}}

  

 

Iii. Reflection of member variables
ClassUtil:
/*** Get member variable information ** @ param obj */public static void printFieldVariableMessage (Object obj) {Class c = obj. getClass ();/*** the member variable is also the object * java. lang. reflect. the Field * Field class encapsulates the operation on member variables * The getField () method obtains information about all public member variables * getDeclaredFields () the method obtains information about the member variables declared by the class. */Field [] fs = c. getDeclaredFields (); for (Field field: fs) {// obtain the Class type of the member variable. Class fieldType = Field. getType (); String typeName = fieldType. getName (); // get the name of the member variable String fieldName = field. getName (); System. out. println (typeName + "" + fieldName );}}

  

Iv. constructor reflection
ClassUtil:
/*** Get the constructor information ** @ param obj */public static void printConMessage (Object obj) {Class c = obj. getClass ();/*** the constructor is also an object * java. lang. constructor encapsulates the Constructor information. * getConctructots obtains all public Constructor. * getDeclaredConstructors obtains the self-declared Constructor * // Constructor [] cs = c. getConstructors (); Constructor [] cs = c. getDeclaredConstructors (); for (Constructor constructor: cs) {System. out. print (constructor. getName () + "("); Class [] paramtypes = constructor. getParameterTypes (); for (Class class1: paramtypes) {System. out. print (class1.getName () + ",");} System. out. println (")");}}

 

V. Java class loading mechanism

MethodDemo1:

Public class MethodDemo1 {public static void main (String [] args) {// obtain the print (int, int) method A a1 = new A (); Class c = a1.getClass (); /*** get Method, name and parameter list * getMethod gets the public Method * getDelcaredMethod gets its own declared Method */try {// Method m = c. getMethod ("print", new Class [] {int. class, int. class}); Method m = c. getMethod ("print", int. class, int. class); // a1.print (); Reflection operations of methods use m objects to call Methods // if no return value is returned, null is returned, returns the specific return value Object o = m. invoke (a1, new Object [] {10, 20}); System. out. println ("=================="); Method m1 = c. getMethod ("print", String. class, String. class); o = m1.invoke (a1, "hello", "world"); Method m2 = c. getMethod ("print"); m2.invoke (a1);} catch (Exception e) {e. printStackTrace () ;}} class A {public void print () {System. out. println ("hello world");} public void print (int a, int B) {System. out. println (a + B);} public void print (String a, String B) {System. out. println (. toUpperCase () + "," + B. toUpperCase ());}}

MethodDemo2:

Public class MethodDemo2 {public static void main (String [] args) {ArrayList list = new ArrayList (); ArrayList <String> list1 = new ArrayList <String> (); list1.add ("hello"); Class c1 = list. getClass (); Class c2 = list1.getClass (); System. out. println (c1 = c2 ); // true/*** c1 = c2 returns true, indicating that the generic type of the set is de-generic after compilation * the generic type integrated in Java prevents incorrect input, it is valid only in the compilation phase * bypassing the compilation will be invalid */try {Method m = c1.getMethod ("add", Object. class); m. invoke (list1, 100); // The compiled operation bypasses the generic System. out. println (list1.size (); System. out. println (list1); // you cannot use the foreach operation at this time. ClassCastException} catch (Exception e) {e. printStackTrace ();}}}

  

 

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.