Java ClassLoader, Reflection

Source: Internet
Author: User

Bytecode object, when we save the program generated by the. class file is a compiled file, when we run the program, the program to read the. class file, the file will be stored in memory, in the heap to create a. class file Object

When a program wants to use a class, the class is not yet in memory, and it is initialized by loading, connecting, and initializing 3 steps.

Load, load the class file object into memory, create a class object, and any class will create a class object when it is used

Connection, 1. Check the syntax for problems, coordinate with other classes

2. Prepare to initialize values for static member variables

3. Parsing, changing the symbolic reference to a direct reference

For example: int a = 1; parsing is changing a directly to 1.

When classes are initialized

1. When creating a class

2. Static methods for classes

3. When a static member variable of a class is assigned a value

4. Reflection when creating a class

5. When a subclass of a class is called

6. When running the program directly

Class is composed of loaders

Reflection

For any of the classes in Java, we can know his methods and properties, for any one object, we can call his methods and properties, dissection, this is called the Java reflection mechanism

first we want to get the bytecode object for this class and manipulate it.

There are 3 different ways

Let's start by creating a class person

1  Packagecom.orcale.damo01;2 3  Public classPerson {4      PublicString name;5     Private intAge ;6     Static{7System.out.println ("Static code block");8     }9      PublicPerson () {TenSYSTEM.OUT.PRINTLN ("Null parameter construction"); One     } A      PublicPerson (String name,intAge ) { -          This. name=name; -          This. age=Age ; theSystem.out.println ("With reference structure"); -     } -     PrivatePerson (intage,string name) { -          This. Age =Age ; +          This. name=name; -System.out.println ("With reference structure"); +     } A      Public voideat () { atSystem.out.println ("Eat"); -     } -      Public voidWork (String name) { -System.out.println (name+ "Walk"); -     } -     Private voidRun (String name) { inSystem.out.println (name+ "Running"); -     } to @Override +      PublicString toString () { -         return"Person [name=" + name + ", age=" + Age + "]"; the     } *}

Get a bytecode object from an object

1 New Person (); 2 Class c = P.getclass ();
System.out.println (c);

Get By class name

1 Class c1 = person. class;

Get forname (completed class name, package name) by using class's static method

1 Class c2 = class.forname ("Com.orcale.damo01.Person"); 2 System.out.println (C2);

Get the public constructor method

1 Class c = person. class ; 2 Constructor con =C.getconstructor (This is the case if there is a parametric construct);
is expressed as
Constructor con =c.getconstructor (sting.calss,int.class) data type in front, class in the back, specific to the construction parameters
3 System.out.println (con);

Get all of the common construction methods

1     Class C = person. class ; 2         Constructor[] con = c.getconstructors ();   An array of objects, putting all the construction methods in 3for         (Constructor co:con) {4             SYSTEM.OUT.PRINTLN (co); 5         }

Get the Public method

1Class C = person.class;2Constructor con =c.getconstructor (String.class,int.class);3         //because there is no single constructor for string name in the person class, 2 are written,4Object obj =c.newinstance ();5         //Create an object ancestor class, and then get the method with the bytecode object6         //GetMethod ("First write the method name that needs to be called", write the parameters that need to be passed in);7Method me = C.getmethod ("Work", String.class);8         //call method with the Invoke method (the first write object, the second one that requires an argument to be passed in)9Me.invoke (obj, "xiaoming");

Get all the public methods and get all the public constructor methods almost, the entire array traversal can be

Get all the public member variables

1 Class c= person. class ; 2         Field[] f= c.getfields ();  Array 3for         (field ff:f) {4             by Field "" Method SYSTEM.OUT.PRINTLN (FF); 5         }

Gets the specified public member variable

1 Class c= person. class ; 2         Field f= C.getfield ("name"); 3         System.out.println (f);

Modifying a public member variable assignment

1 Class c= person. class ; 2         Field f= C.getfield ("name"); 3         Object obj = c.newinstance (); 4         // call the Set method to assign a value to name, and then output the object's properties 5         F.set (obj, "xiaoming"); 6         System.out.println (obj)

Get the private constructor method

The principle is through the Setaccessible method, avoid the class of the loader to check the class, do not recommend the private construction method and property operations, otherwise private do what is meaningless

1     Class c =person. class ; 2         Constructor con = c.getdeclaredconstructor (int.  Class, String. class ); 3         Con.setaccessible (true); // Violent reflex Switch 4         Object obj =  con.newinstance ("DD");    5         System.out.println (obj);

Get a Private member variable

Class c= person. class ;         = C.getdeclaredfield ("Age");  // get a Private member variable        Object obj = c.newinstance ();        Field.setaccessible (true);  // Violent Switch        Field.set (obj, one);           System.out.println (obj);

Exercise: Have a aarraylist<string> list and add int type data to it, generic erase (no generics in bytecode file)

1 New Arraylist<string>(); 2         Arr.add ("abc"); 3         Class c= arr.getclass (); 4         Method addd = C.getmethod ("Add", Object.  Class); 5         Addd.invoke (arr, 1); 6          for (Object obj:arr) {7            System.out.println (obj); 8         }

Java class loader, reflection

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.