Java Learning Lesson 64th-reflection mechanism

Source: Internet
Author: User
Tags throw exception

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class , for any object, it can be called any of its methods and properties, the dynamic acquisition of information and the function of the dynamic method of invoking the object is called the Java language reflection mechanism, simply said: can dynamically get the information in the class (All the Class), is the reflection of Java, Can also be understood as the anatomy of a class

Basic application scenarios for reflection mechanisms:

For example, a program application (TOMCAT), in order to improve its extensibility, will expose an interface , the external definition of a class implementation of this interface, but within the application can not new objects, so the application will provide a configuration file , It is the basic application of the reflection mechanism that the interface user can write the class name that is written and implement the interface into the configuration file, and the application uses the reflection mechanism to fetch the bytecode file of the class of the specified name and load the contents of it.

Summary: The reflection technology improves the extensibility of the program, and the application is simple, the bridge between the user and the program becomes the configuration file

To dissect a class file, just get the bytecode file for that class.

The reality of things, constantly upward extraction of its common content, you can get classes to describe things, reflection mechanism, is also the byte code upward extraction, with class to describe the bytecode file, then you can produce objects, you can provide methods to get the members of the bytecode file, such as: Name, field, constructor, All content, such as general functions, reflection is done by the class.

Defining a Presentation Class

public class Mans {private int age;private String name;public man () {super (); System.out.println ("man Run");} Public Mans (int age, String name) {super (); this.age = Age;this.name = name; System.out.println ("Man run Yes" +this.name+this.age);} public void Show () {System.out.println (age+): Show: " +name);} private void Privatemethod () {System.out.println (age+ "): Method: " +name);} public void print (int num,string line) {System.out.println (num+): Print: " +line);} public static void Staticmethod () {System.out.println (". Staticmethod. ");}}

Get class object mode

To dissect a bytecode file, you must obtain a byte-code file object

There are three ways to get a byte-code file object:

GetClass methods in the 1.Object class
In this way, you must define the specific class and create the object

public static void Get_class_object () {Mans man1 = new Man ();    class<?> clas1 = Man1.getclass ();    Mans man2 = new Man ();    class<?> clas2 = Man2.getclass ();        System.out.println (CLAS1==CLAS2);}

2. Any data type has a static property. class to get its corresponding class object
Relatively simple, but still need to define static members of the class, extensibility is not high

public static void Get_class_static () {class<?> cls1 = Man.class; class<?> cls2 = Man.class; System.out.println (CLS1==CLS2);}

3. The class can be obtained by the string name of the given class (key mastery)
You can do this with a method in class

The method is forname (); This is the only way to have a name

API:forName(String className)
Returns the object associated with the class or interface with the given string name Class .

API:forName(String name, boolean initialize,ClassLoader loader)
Returns the object associated with the class or interface with the given string name, using the given class loader Class .

public static void Get_class () throws ClassNotFoundException {//g:\java\fan\bin\fan\man.class//The default classpath path is SRC, binstring classname = "fan." Man ";//clear which package is in the class class<?> CLS = Class.forName (classname); SYSTEM.OUT.PRINTLN (CLS);}
Attention Throw Exception

Gets the constructor in class

Man mans = New Man (); the previous new object, based on the name of the class being new, looks for the class's bytecode file, loads it into memory, creates the bytecode file object, and then creates the man object corresponding to the byte-code file.

API:newInstance()

Creates a new instance of the class represented by this class object. It is like instantiating the class with an expression with an empty argument list new . If the class has not been initialized, initialize the class.

is actually the constructor of the null parameter in the man

There are null parameter constructors in the man class

public static void Reflect_demo () throws ClassNotFoundException, Instantiationexception, illegalaccessexception { String classname = "fan." Man ";//Search for the name class file and load into memory, resulting in class object class<?> CLS = Class.forName (classname); object obj = Cls.newinstance ();}

no null parameter constructor in man class

Man mans = New Man (One, "a");

If you call the above method directly, the initialization exception is thrown instantiationexception

If there is an empty parameter constructor, however, it is private to the privately man () {}, An invalid access exception is thrown illegalaccessexception

So: When you get the object that is represented in the specified name class, and object initialization does not use NULL argument constructs, you should first get its constructor, which is done with the bytecode file object, GetConstructor

API:getConstructor(Class<?>... parameterTypes)
Returns an Constructor object that reflects the Class specified public construction method for the class represented by this object.

API:getDeclaredConstructors()
Returns Constructor an array of objects that reflect all of the Class constructor methods for the class declaration represented by this object.

andConstructor对象中有方法new对象

API:newInstance(Object... initargs)
Use the Constructor constructor method represented by this object to create a new instance of the Declaration class for the constructed method, and initialize the instance with the specified initialization parameters.

public static void Reflect_demo () throws Exception {String classname = "fan. Man "; Class<?> cls = class.forname (classname);//parameter array, byte code corresponding to an int base data type is int.classconstructor<?> constructor = Cls.getconstructor (Int.class,string.class);//Gets the object of the specified constructor objects obj = constructor.newinstance (one, "a");}

It is only necessary to specify the class name and the parameter information of the constructor in the configuration file.

PS: Generally reflected classes are usually with null parameters, because it is convenient to get the instance

Get the fields in class

API:getField(String name)
Returns an Field object that reflects the Class specified public member field of the class or interface represented by this object.

API:getFields()
Returns an array containing some Field objects that reflect Class all accessible public fields for the class or interface represented by this object.

API:getDeclaredField(String name)
Returns an Field object that reflects the Class specified declared field of the class or interface represented by this object.

API:getDeclaredFields()
Returns Field an array of objects that reflect Class all the fields declared by the class or interface represented by this object.

public static void Reflect_demo () throws Exception {String classname = "fan. Man "; Class<?> cls = class.forname (classname); Object object = Cls.newinstance ();//field Field = Cls.getfield ("name");// There is the age, Name field and can only get public field field = Cls.getdeclaredfield ("name");//can only get this class, including private System.out.println (field);//Get the value of the field .....//object obj = Field.get (Object); System.out.println (obj);//The rhetorical question fails because it is private//access to private fields is checked for,-> brute force access field.setaccessible (TRUE);//field's parent class method, Modify its access rights Field.set (object, "a");//Set the value of object obj = Field.get (object); System.out.println (obj);//}

The Api:accessibleobject class is the base class for Field, Method, and Constructor objects. It provides the ability to mark reflected objects as being used to cancel the default Java language access control check.

PS: Accessing data in a brute-force manner is not recommended

Gets the method in the specified class

Get a non-parametric method

public static void Reflect_demo () throws Exception {String classname = "fan. Man "; Class<?> cls = class.forname (classname);//method[] methods = Cls.getmethods ();//Get all public methods of this class and its parent class//methods = Cls.getdeclaredmethods ();//Only get all methods in this class, including private//for (method M:methods) {//system.out.println (M);//}//take an argument method method = Cls.getmethod ("show", null);//note with the constructor function, the name, method parameter list//object obj = Cls.newinstance ();//non-parametric construction//method.invoke ( obj, null); constructor<?> Constructor = Cls.getconstructor (int.class,string.class); Object obj = constructor.newinstance (1 , "a");//Method.invoke (obj, null);//The underlying method represented by this method object is called on the specified object with the specified argument. }

get the parameter method

public static void Reflect_demo () throws Exception {String classname = "fan. Man "; Class<?> cls = class.forname (classname); Method method = Cls.getmethod ("print", int.class,string.class);//methods parameter list Object obj = Cls.newinstance (); Method.invoke ( obj, one, "a");//Call to the method being acquired}


Reflex Exercises:

public class Computer {public void run () {System.out.println ("Computer is run ..."); public void Useinter (Inter p) {//externally exposed interface, increase extensibility if (p!=null) {P.open ();p. Close ();}}} Public interface Inter {public void open ();p ublic void Close ();} public class Netcard implements inter{public Void Open () {System.out.println ("netcard open ..."); public void Close () {System.out.println ("netcard close ...");}} public class Soundcard implements Inter {public void open () {System.out.println ("Soundcard open ..."); public void Close () {System.out.println ("soundcard close ...");}} public class Main {public static void main (string[] args) throws exception{computer com = new computer (); Com.run ();//com.u Seinter (New Soundcard ());//polymorphic, but this write needs to modify the existing code//Use the radiation mechanism to complete, get the class file, the internal implementation of the creation of the object file Confile = new file ("g:\\java\\fan\\ Bin\\fan\\inter.properties "); Properties Pro = new properties (); FileInputStream fis = new FileInputStream (confile);p ro.load (FIS);//load the information in the stream into the collection for (int x = 0; x < pro.size (); + +) { String Intername = Pro.getpropertY ("Inter" + (x+1)); Class<?> cls = Class.forName (intername);//class to load this inter subclass object obj = Cls.newinstance ();//Create Inter object inter p = ( Inter) obj;com. Useinter (P);} Fis.close ();}}

because we haven't learned XML yet, I use properties instead



Java Learning Lesson 64th-reflection mechanism

Related Article

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.