Dark Horse programmer--reflection

Source: Internet
Author: User

-------<a href= "http://www.itheima.com" target= "blank" >android training </a> <a href= "/http/ Www.itheima.com "target=" blank ">java training </a>, look forward to communicating with you! ----------

I. Overview

Reflective technology:

The reflection technique can dissect a class.

Second, the application scenario

Provides a configuration file to extend functionality for classes that implement this program later. Provide configuration files externally, so that later subclasses can directly configure the class name to the configuration file. The application reads the contents of the configuration file directly. and find the same class file as the given name. Do the following:

1) Load this class.

2) Create an object of the class.

3) Call the contents of the class.

When an application uses a class that is not deterministic, it is possible to have the user store the specific subclass in the configuration file by providing a configuration file. The program then uses the reflection technique to obtain the content of the specified class.

Benefit: The reflection technology greatly improves the expansibility of the program.

Reflection is the mapping of the various components in the Java class into the corresponding Java classes.

Iii. the difference between class and class

1) The classes in Class:java are used to describe the generality of a class of things, what the attributes of such things are, and what the value of this property is, then the instance object of this class determines that different instance objects have different property values.

2) class: Refers to the Java program in each Java class is the same thing, are Java program classes, these classes are called class. For example, people correspond to the person class, and the Java class corresponds to class. Class is the generic term for each Java class in a Java program, and it is the cornerstone of reflection, using reflection through class classes.

Four, constructor class

1. Overview

If the specified class does not have a constructor for an empty argument, or if the class object to be created needs to be initialized by the specified constructor. What then? You cannot use the Newinstance method in class classes at this time. Now that the object is initialized by the specified constructor. You must first obtain this constructor--constructor. Constructor represents a constructor method for a class.

2, get the construction method:

1) Get all the constructor methods for this class: such as getting all the constructor methods of the person class in the example above

Constructor[] cons = Class.forName ("Cn.itheima.Person"). GetConstructors ();

2) Get a constructor method:

Constructor Con=person.class.getconstructor (String.class,int.class);

3. Create an Instance object:

1) usual way: person p = new person ("Lisi", 30);

2) Reflection mode: Person p= (person) con.newinstance ("Lisi", 30);

Note:

1. When you create an instance, the argument list in the Newinstance method must match the parameter list in the method GetConstructor methods that get constructor.

2. newinstance (): Constructs an instance object that constructs an object each time it is called.

3. The advantage of using the constructor class to create a class instance is that you can specify a constructor, and the class class can only use the parameterless constructor to create an instance object.

V. Field class

1. Field class represents a member variable in a class

2. Methods

Field GetField (String s);//access to public and parent classes only

Field Getdeclaredfield (String s);//gets any member variable in the class, including the private

Setaccessible (ture);

If it is a private field, the ability to first remove the permission check for that private field. Also known as violent visits.

Set (Object obj, object value);//sets the field represented by the specified object variable to the specified new value.

Object get (Object obj);//Returns the value of the field represented on the specified object.

Vi. type of method

1. Overview: The method class represents one of the member methods in a class. Call a method on an object, get the method first, and then invoke it on an object.

2. Expert mode: Who calls this data, is the expert who calls it.

If a person closes:

Caller: Is the door call off the action, the object is the door, because the door knows how to perform the action, through the door axis and other details to achieve.

Conductor: is the person in the command door do the action, just to the door issued a signal, let the door to execute.

Summary: The use of variables, the method itself knows how to implement the process, that is, "method Object" Call method, only executed the method of every detail.

3. Methods

Method[] GetMethods ();//Get only methods in the public and parent classes.

Method[] Getdeclaredmethods ();//Get private in this class.

Methods GetMethod ("Method name", parameter. Class (null if null));

Object Invoke (Object obj, parameter);//Call method

If the method is static, the object argument in the Invoke method can be null.

Seven, the reflection of the array

1. An array of the same dimension and element type belongs to the same type, that is, with the same class instance object. The name of the array bytecode: there are [and arrays of corresponding types of abbreviations, such as int[] array name: [I

2, object[] and string[] There is no parent-child relationship, Object and String have a parent-child relationship, so new object[]{"AAA", "BB"} can not be cast to the new string[]{"AAA", "BB"}; Object x = "abc" can be cast to string x = "abc".

3. How to get the type of an element in an array,

Cases:

int a = new int[3];object[] obj=new object[]{"ABC", 1};

Cannot get the specific type of an array, only the type of one of the elements.

Such as:

Obj[0].getclass (). GetName () got java.lang.String.

4. The array tool class is used to complete the reflection operation of the array.

Array.getlength (Object obj);//Gets the length of the array

Array.get (Object obj,int x);//Gets the elements in the array

5, a one-dimensional array of the basic type can be used as object type, not as object[] type, non-primitive type of one-dimensional array, can be used as object type, and can be used as the object[] type.

Viii. Analysis of Hashcode

Overwrite the meaning of the Hashcode () method: The Overwrite Hashcode () method is only valuable if it is deposited with a set of hashcode algorithms.

1, the origin of the hashing algorithm:

If you look for an object in a collection, it is usually a one-off comparison, and then you have to compare equals when you find it, the object is very long and the efficiency is very low. There is a hashcode algorithm, there is a set, the set into a number of areas, each stored in the object, you can calculate a hashcode value, according to the calculated value, put into the corresponding area. When looking for an object, just work out the hashcode value of the object, look at the area, and then go to the appropriate area to see if there is an object equal to the object. This improves the performance of the lookup.

2, if you want to hashcode the value of the method, the premise is that the object is stored in the hash algorithm of this type of collection of value. If you do not deposit in a collection that is a hashcode algorithm, you do not have to replicate this method.

3, if there is no replication Hashcode method, the Hashcode value of the object is calculated according to the memory address. This way, even if the contents of the two objects are to be waited for, the memory address values in the collection are different, resulting in a different hashcode value, and the area being deposited is different. So two objects of equal content can be stored in the collection.

So there is a saying: If two objects equals equal, you should make their hashcode equal. If the object is not stored in a collection based on the hash algorithm, the replication Hashcode method is not required.

4. When an object is stored in the HashSet collection, it is not possible to modify the fields in the object that participate in the hash value, otherwise the modified hash value of the object is different from the hash value originally stored in the HashSet collection. In this case, calling the Contains method or the Remove method to find or delete a reference to the object will not find the object. This results in the inability to delete the current object from the HashSet collection individually, resulting in a memory leak. (Some objects in the program are no longer used, thought to be deleted, but not, still in memory, when such objects slowly increase, it will cause memory leaks.) )

Ix. the effect of reflection

I. Overview

1. Framework: A way to invoke a Java class by reflection.

such as real estate business house users, doors and windows and air-conditioning and so on are installed by users themselves, the house is the framework, users need to use this framework, safe doors and windows into the framework provided by the real estate developers.

The difference between a framework and a tool class: The tool class is called by the user class, and the framework calls the user-supplied class.

2, the framework of the core machinery to solve the problem:

When we write the framework (the process of building the house), the calling class (Installed doors and windows, etc.) does not appear, then the framework cannot know the class name to be called, so in the program it is not possible to directly new the instance object of one of its classes, but to use reflection.

3, the Simple framework procedure steps:

1) Right-click the project file name a profile such as: Config.properties, and then write the configuration information. such as the key-value pair: Classname=java.util.arraylist, the right-hand configuration key, and the value on the right.

2) Code implementation, loading this file:

① reads the file into the read stream and writes out the absolute path to the configuration file.

such as: InputStream is=new fileinputstream ("configuration file");

② uses the Properties class's load () method to store the data in the stream into a collection.

③ closed stream: The read stream is closed because the data in the stream is already loaded into memory.

3) Obtain the classname by using the GetProperty () method, that is, the configured value, that is, a class name.

4) Create the object Newinstance () in a reflective manner.

5) Execute the program body function

Second, class loader

1, Summary: Class loader is to load the. class file into memory, or you can load the information in the normal file into memory.

2, the file loading problem:

1) Eclipse compiles all. java files from the source program into a. class file and then puts it in the directory specified by Classpath. The non-. Java files will be copied intact into the directory specified in the. class. At run time, the. class file is executed.

2) Put the configuration files together in the. class file directory and the ClassLoader will load together.

3. Load the resource file: Use the class loader.

1) loaded into memory by the ClassLoader ClassLoader, which takes the class loader with the getClassLoader () method and then loads the configuration file (resource file) into memory using the class loader's getResourceAsStream (String name) method. Using the ClassLoader to load the configuration file, you need to write the package name that is placed on the configuration file. This method is only read function.

2) class also provides the getResourceAsStream method to load the resource file, in fact, it is called the ClassLoader method inside. At this point, the configuration file is relative to the current directory of the class file, that is, in this way, the configuration file can be omitted before the package name.

such as: Class name. Class.getresourceasstream ("Resource file name")

4, the path of the configuration file problem:

1) Use the absolute path, through the Getrealpath () method to calculate the specific directory, rather than the internal code out.

Generally first get the user-defined total directory, in addition to their own internal path. You can get the file path through the Getrealpath () method. A configuration file modification is required to be stored in a configuration file, so the absolute path to it is needed, so the configuration file is placed inside the program.

2) name path problem:

① if the configuration file and the Classpath directory do not matter, you must write the absolute path,

② if the configuration file and the Classpath directory are related, that is, in the Classpath directory or in its subdirectories (typically the Resource folder Resource), then the relative path must be written because it knows for itself which package it belongs to, relative to the current package.

Dark Horse Programmer--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.