1. Basic concepts
The concept of reflection was first proposed by Smith in 1982. It mainly refers to the ability of a program to access, detect and modify its own state or behavior, and adjust or modify the state and related semantics of the behavior described by the application according to the state and results of its own behavior. Reflection is a powerful tool in Java. It enables you to create flexible code that can be configured at run time without source code links between components. Reflection allows us to access the internal information of the classes loaded into the JVM when writing and executing, rather than the code cooperating with the selected classes in the source code. This makes reflection the main tool for building flexible applications. However, it should be noted that if used improperly, the cost of reflection is very high.
2. Function
Bytecode files can be manipulated through the reflection mechanism in the Java language. When the program is running, the Java system will always carry out the so-called runtime type identification for all objects. This information records the class to which each object belongs. This information can be accessed through specialized classes. The class used to store this information is the class class, which provides powerful functions for writing dynamically manipulated java code programs.
3. Build Class object
//Method 1: Class.forName(); try { // The first way to construct a Class object Class clazz = Class.forName("java.lang.String"); Object obj = clazz.newInstance(); System.out.println(obj); } catch ( ClassNotFoundException e ) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch ( InstantiationException e) { e.printStackTrace(); } //Method 2: class try { // The second way to construct a Class object Class stringClass = String.class; System.out.println(stringClass); } catch ( ClassNotFoundException e ) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch ( InstantiationException e) { e.printStackTrace(); } //Method 3: Object.getClass() try { // The third way to construct a Class object String s = "s"; stringClass = s.getClass(); System.out.println(stringClass); } catch ( ClassNotFoundException e ) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch ( InstantiationException e) { e.printStackTrace(); }
4. Main classes and methods in java reflection
Class: related classes of reflection mechanism are in java.lang.reflect. *; Bao Xia
java.lang.Class: Represents the entire bytecode, represents a type, and represents the entire class. java.lang.reflect.Method: Represents the method bytecode in bytecode. Represents a method in a class. java.lang.reflect.Constructor: Represents the construction method in bytecode.Represents the construction method in the class java.lang.reflect.Field: Represents the attribute bytecode in bytecode.Represents member variables (static variables) in a class+Instance variable).
method:
1.getConstructors();//Get construction method 2.getDeclaredMethods();//Get method in class 3.getDeclaredFields();//Get properties in class 4.getName(); //Get method / class / property name 5.getModifiers();//Get method modifier 6.getParameterTypes();//Get method modifier 7.getReturnType();//Gets the return value type of the method 8.getType();//Get variable type 9.get();//Gets the value of the variable 10.getInterfaces();//Get interface name 11.getSuperclass();//Gets the parent class of the class object 12.getPackage();//Get the package name 13.newInstance();//Get class object 14.setAccessible(true);//Private settings are accessible 15.set();//Assign values to variables in objects 16.getMethod("Method name");//Reflection call of object method; 17.invoke();//Call static method
5. Path problem
String path / InputStream in = Thread.currentThread().getContextClassLoader().getResource("Write relative path, but this relative path from src Start looking").getPath(); //This method is to obtain the absolute path of a file
6. Quickly bind attribute resource files
ResourceBundle bundle = ResourceBundle.getBundle("route"); String value = bundle.getString(key); //requirement: //First, this file must be in the classpath //Second, the file must end with. properties
7. Reflection and safety
Security is a complex problem when dealing with reflection. Reflection is often used by framework code. Because of this, we may want the framework to fully intervene in the code without considering the conventional intervention restrictions. However, in other cases, uncontrolled intervention can pose serious security risks, such as when the code is running in an environment of untrusted code sharing.
8. Disadvantages of reflection
Performance issues. Using reflection is basically an interpretation operation. We can tell the JVM what we want to do and it meets our requirements. For field and method access, reflection is much slower than direct code. The extent of the performance problem depends on how reflection is used in the program. If it is a relatively small part of the program running, slow performance will not be a problem.
Using reflection blurs what actually happens inside the program. Programmers hope to see the logic and reflection of the program in the source code. Technologies that bypass the source code will bring maintenance problems. Reflective code is more complex than the corresponding direct code. The best way to solve these problems is to use reflection conservatively -- only where it can really increase flexibility -- to document its use in the target class.
9. Supplement
You only want the "static code block" of a class to execute:
Class.forName("class name of the class"); In this way, the class is loaded. When the class is loaded, the static code block is executed. Here, I am not interested in the return value of this method, mainly to use the action of "class loading".
2, Annotation1. Concept of annotation
Annotation is that Java provides a way and method to associate any information and metadata with elements in a metaprogram. Annotation is an interface. The program can obtain the annotation object of the specified program element through reflection, and then obtain the metadata in the annotation through the annotation object.
2. Role of annotations
Document writing: generate documents through the metadata identified in the code.
Code analysis: analyze the code through the metadata identified in the code.
Compilation check: the compiler can realize basic compilation check through the metadata identified in the code.
3. Basic built-in notes
@The Override annotation enables compile time checking. You can add this annotation to your method to declare that the method is used to Override the method in the parent class. If the method is not a method that overrides the parent class, an error will be reported in the compilation. For example, if we rewrite the toString () method for a class, but write it toString (), and we add the @ Override annotation to the method, the compilation cannot pass.
@Deprecated is used to add comments on methods that should not be used. When programmers use these methods, a prompt will be displayed at compile time. It has the same function as the @ deprecated tag in javadoc.
@SuppressWarnings is different from the previous two comments. You need to add a parameter to use it correctly. These parameter values have been defined. We can use them selectively. The parameters are as follows:
- Warning when deprecation uses an obsolete class or method
- Unchecked warning when unchecked conversion is performed, for example, when using a collection, generics is not used to specify the type of collection storage
- fallthrough the warning when the Switch block leads directly to the next situation without breaking
- Path warning when there is a nonexistent path in the classpath, source file path, etc
- serial warning when a serialVersionUID definition is missing on a serializable class
- Finally warning when any finally clause cannot complete normally
- All the police about all the above
4. User defined annotation type
public @interface NewAnnotation { } public class AnnotationTest { @NewAnnotation public static void main(String[] args) { } }
5. Use of notes
class child extends Father { @Override //Indicates that the subclass overrides the method of the parent class public void test(){ } } @Deprecated //The classes, methods, variables, etc. modified by @ Deprecated represent those that are not recommended public String convertDate(String date) { return new Date(date).toString(); } @SuppressWarnings("all") //Suppress all types of warnings public void addItems(String item){ List items = new ArrayList(); items.add(item); }