Reflection Overview:
An already written application, to add new features later, but generally cannot get the source of the application, can not directly in the application to create objects with new, what should I do? Since the subclass is not deterministic, you can store the indeterminate information in the configuration file by providing the configuration file externally. The application needs to write at design time how to read the configuration file information? What to do, first store the specified subclass name, find the class according to the specific name and load and create objects, these actions are written in the early definition of the software. The action to create the object is completed before the class has been created. This is the dynamic acquisition of the specified class and the use of functionality in the class, which is the reflection technique. The appearance of reflection technology has greatly improved the expansibility of the program. What classes you can use to provide what classes.
Use of Reflection:
/** Create Objects* Previous Practice: * Person p = new person (); * P.show (); * Reflection: In fact, the content of the class file to use the members of the classes themselves. * Members: member variables, constructor methods, member methods. * Reflection actually means that we go through the bytecode file object to use the class's member variables, construct methods, and member methods. * What is a byte-code file object? * Zhang San, John Doe, Harry, they had something in common, so we pulled out a person class. They are all objects of the person class. * Take a look at: * Person.class,student.class,teacher.class * Extract the contents of these class files and eventually form a class: class. The object of this class is then a byte-code file object. * How do we get to the bytecode file object? * A: Through the GetClass () method of the object class. * Person P = new person (); * Class C = p.getclass (); * B: Class static data of the data type. * Class C3 = Person.class; * SYSTEM.OUT.PRINTLN (c = = C3); * A static method of the C:class class: * forname (String className) * Class C4 = class.forname ("Cn.itcast_01.Person"); * * Development Why use the Third Kind? * The Third Way is to provide the path through the configuration file. *//** Get the construction method through reflection and use. * * in reflection, it has encapsulated the construction method, the member variable, and the member method as objects. * * Constructor: Constructor Method Object * Field: Member Variable Object * Method: Member Method object * * person p = new Person (), * System.out.println (p), * null---0 */public class Reflectdemo {public static void main ( String[] args) throws Exception {//Get bytecode file object Class c = Class.forName ("Cn.itcast_01.Person"); //get construction Method--the corresponding object//Co Nstructor[] cons = C.getconstructors (); All public construction methods//constructor[] cons = C.getdeclaredconstructors (); All construction methods//for (Constructor con:cons) {//System.out.println (con);//} //How do I get a single constructor object?//public Constructor GetC Onstructor (Class ... parametertypes)//class ... is actually the form of multiple construction methods. You pass a few arguments, and I get the constructor object with a few arguments. Instead of the corresponding data type, the class file object for that type is passed. Constructor con = c.getconstructor (); The non-Parametric construction method//system.out.println (con); //public t newinstance (Object ... initargs)//The returned T is actually an object created from the constructor. Object ... is actually the actual parameter. Object obj = con.newinstance (); Creates an object from a parameterless constructor object. system.out.println (obj); Null---0}}/* * * * person p = new person (); * p.name = "Wu Xin"; * System.out.println (P); * Wu Xin---0 */ public class Reflectdemo {public static void main (string[] args) throws Exception {//Get bytecode File object class C = Class.forName ("cn . Itcast_01.person "); //gets all member variable objects//field[] fields = C.getfields (); Gets the public member variable//field[] fields = C.getdeclaredfields (); Get all member variables//for (field Field:fields) {//System.out.println (field);//} //Create an object by using the parameterless construction method Constructor con = C.getco Nstructor (); Object obj = Con.newinstance (); System.out.println (obj); Null---0 //we want to get A//Field namefiled = C.getfield ("name"); Gets the member variable object named name by byte-code file Object Field namefiled = C.getdeclaredfield ("name"); Gets the member variable object named name through the bytecode file object //How to obtain a public member variable, using GetField (), or Getdeclaredfield () if it is not public. If the obtained member variable object is public, it is used directly. If it is not public, it cannot be used directly. This time, by violent reflection. Namefiled.setaccessible (true); //Obj.namefield = "Wu Xin";//how do you achieve this effect?//public void Set (Object obj,object value) Namefiled.set (obj, "Wu Xin"); To the name of objThe filed is assigned a value of "Wu Xin" system.out.println (obj); Wu Xin---0 //continues to assign the value field Agefield = C.getdeclaredfield ("Age"); Agefield.setaccessible (true); Agefield.set (obj, 18); System.out.println (obj); Wu Xin---18}}/* * reflection Gets the member method * reflection using Steps: * * construction method: Gets the bytecode file object, gets the constructor object through the bytecode file object, and creates the object from the constructor object. * * member Variable: Gets the bytecode file object, gets the member variable object through the bytecode file object, and assigns a value to the object through the member variable object call method. * * member Method: Gets the bytecode file object, gets the member method object through the bytecode file object, and invokes the method through the member method object. * gets the member method by reflection and uses it. */public class Reflectdemo {public static void main (string[] args) throws Exception {//Get bytecode File object class C = Class.for Name ("Cn.itcast_01.Person"); //get member Method//method[] methods = C.getmethods (); In addition to the public methods in the parent class//method[] methods = C.getdeclaredmethods (); Own all methods//for (method Method:methods) {//System.out.println (method);//} //Create an object constructor con = c.getconstr Uctor (); Object obj = Con.newinstance (); Create an object using the //Method method m1 = C.getmethod ("show");//OBJ.M1 ();//public object Invoke (object Obj,object ... args )//object is the return value//object obj is a call to the method of the objects//(. args) is the actual parameter of the method M1.invoke (obj); Call the M1 method of the Obj object system.out.println ("----------------------------");//public void print (String name) m2 = C.getmethod ("Print", String.class); M2.invoke (obj, "haha"); system.out.println ("----------------------------");//Public String getString () Method m3 = C.getmethod ("getString"), Object o = M3.invoke (obj); System.out.println (o); system.out.println ("----------------------------");//Public String returnstring ( String name, int age) Method m4 = C.getmethod ("returnstring", String.class, Int.class); Object oo = M4.invoke (obj, "Hello", 100); System.out.println (OO); system.out.println ("----------------------------");//private void function () Method M5 = C.getdeclaredmethod ("function"); M5.setaccessible (true); M5.invoke (obj);}} Normal call Mode Testarguments.main (new string[] ("11", "22", "33")), no parent-child relationship in the way of reflection object[] and string[], object has a parent-child relationship with String, so new object[]{"AAA", "BB"} cannot be forced to switch to new string[]{"AAA", "BB"};,object x = "abc" can be cast to String x = "abc". Main.invoke (null, (Object) (New object[]{"AAA", "xxx"}); Cannot call public static void Main (String [] args) Startingclassname =args[0]; MeThod mainmethod=class.forname (startingclassname). GetMethod ("main", String[].class); Mainmathod.invoke (null,new Object[] (New string[]{"11", "22", "33"});//simplified form mainmathod.invoke (null, (Object) New string[]{"11", "22", "33"}); class testarguments{publics static void Main (string[] args) {for (String Arg:args) { System.out.println (ARG);}}} -----------------------------------------------------------------------------------1, an array of the same dimension and element type belongs to the same type, That has the same class instance object (which is compared to value-independent). string[] A1 = new String[8]; string[] A2 = new string[9]; System.out.println (a1.getclass () = = A2.getclass ());//true string[][] a3 = new String[6][4]; System.out.println (A1.getclass (= = A3.getclass ());//Compile Error 2, the Getsuperclass () method that represents the class instance object of the array returns the class that corresponds to the object class. System.out.println (A1.getclass (). Getsuperclass (). GetName ()); a one-dimensional array of 3, a primitive type can be used as an object type and cannot be used as a object[] type A one-dimensional array of non-basic types that can be used as an object type and as a object[] type. The 4, Arrays.aslist () method handles int[] and string[] differences. Int[] A = new Int[3];object obj = a;//object[] Obj1 = A//error! object[] Obj3 = a1object Obj4 = a3;if (obj4 instanceof string[][]) {System.out.println (Obj1.getclass (). IsArray ());} * * Here is an analysis of the differences between the Arrays.aslist () method for processing int[] and string[], and the reason that the arrays.deeptostring () method cannot handle int[], but can handle string[]. The 5, Array tool class is used to complete the reflection operation of an array. private static void PrintObject (Object obj) {if (Obj.getclass (). IsArray ()) {int len = array.getlength (obj); for (int i=0;i& lt;len;i++) {System.out.println (Array.get (obj, i));}} else {System.out.println (obj);}} 6, how do I get the element types in the array? Each element object needs to be taken out and then judged by the individual objects, because each of these concrete elements can have different types, such as object[] x = new object[]{"abc", Integer.max}. object[] A=new object[]{"A", 1};a[0].getclass (). GetName ();
Comprehensive Case Study: the application of reflection in the frame/*The ArrayList and HashSet instance objects are created directly with the new statement, demonstrating the Equals and hashcode methods of automatically generating Reflectpoint classes with Eclipse, comparing the running result differences of two collections. Then, instead of creating an instance object of ArrayList and HashSet in the form of a profile plus reflection, compare the observed run result differences.*/
public static void Main (string[] args) throws exception{
You should use ArrayList and hashset directly before introducing a read from the configuration file so that learners can learn.
Properties Props = new properties ();
Show the problem of relative path first
InputStream ips = new FileInputStream ("Config.properties");
/* A class loader can load. class files, which of course can also load other files in the CLASSPATH environment, since it has so much power that it has no reason not to provide such a method in passing. It can also load only those files in the CLASSPATH environment. Note: When you use the ClassLoader directly, you cannot begin with/. */
InputStream ips = ReflectTest2.class.getClassLoader (). getResourceAsStream ("cn/itcast/javaenhance/ Config.properties ");
class provides a convenient way to load a file in the same package directory with the same classloader that loads the current class
InputStream ips = ReflectTest2.class.getResourceAsStream ("config.properties");
InputStream ips = ReflectTest2.class.getResourceAsStream ("/cn/itcast/javaenhance/config.properties");
Props.load (IPS);
Ips.close ();
String className = Props.getproperty ("ClassName");
Class clazz = Class.forName (className);
Collection Collection = (Collection) clazz.newinstance ();
Collection Collection = new ArrayList ();
Reflectpoint pt1 = new Reflectpoint (3,3);
Reflectpoint pt2 = new Reflectpoint (5,5);
Reflectpoint PT3 = new Reflectpoint (3,3);
Collection.add (PT1);
Collection.add (PT2);
Collection.add (PT3);
Collection.add (PT1);
System.out.println (Collection.size ());
}
The simple use of Dark Horse programmer _java reflex