Java reflection and java reflection

Source: Internet
Author: User

Java reflection and java reflection

The reflection of Java is very powerful. It transfers the class and can dynamically generate the class and obtain all information about the class, including its attributes, methods, and constructors, you can even obtain the content in the parent class or parent interface.

The Java reflection mechanism provides the following functions:

  • Determine the class to which any object belongs at runtime;
  • Construct any class object at runtime;
  • Judge the member variables and methods of any class at runtime;
  • Call methods of any object at runtime;
  • Generate a dynamic proxy.

In JDK, the following classes are used to implement the Java reflection mechanism. These classes are located in the java. lang. reflect package.

  • Class: represents a Class.
  • Field Class: represents the member variables of the class (member variables are also called the attributes of the class ).
  • Method class: indicates the Method of the class.
  • Constructor class: Constructor class.
  • Array class: provides static methods for dynamically creating arrays and accessing Array elements.

Reflection

public class ClassDemo {    public static void main(String[] args) throws Exception {        // 1111111111111111111111111111111111111        Person person1 = new Person();        Class c1 = person1.getClass();        Person person2 = new Person();        Class c2 = person2.getClass();        System.out.println(c1 == c2);        System.out.println("============================");        // 222222222222222222222222222        Class c3 = Person.class;        System.out.println(c1 == c3);        System.out.println("============================");        // 33333333333333333333333333333333        Class c4 = Class.forName("com.yydcdut.Reflaction.Person");        System.out.println(c1 == c4);        Constructor co = c4.getConstructor(null);        Object obj = co.newInstance(null);        Method m = c4.getMethod("show", null);        m.invoke(obj, null);        System.out.println("============================");    }}

Perosn class:

public class Person {        public void show()    {        System.out.println("Person--->show");    }}

The project must have only one person. class file, so the objects obtained by reflection are the same.

A usage in a project

package com.yydcdut.test;public class LiSi {    public void show(){        System.out.println("LiSi--->show");    }}
package com.yydcdut.test;public class ZhangSan {    public void show(){        System.out.println("zhangsan--->show");    }}

Create a file named who.txt in the project. content:

whoName=com.yydcdut.test.ZhangSanmethodName=show

In the main class:

Public class MainTest {public static void main (String [] args) throws Exception {Properties prop = new Properties (); FileReader fr = new FileReader ("who.txt"); prop. load (fr); fr. close (); String whoName = prop. getProperty ("whoName"); String methodName = prop. getProperty ("methodName"); // obtain the Class c = Class of the object. forName (whoName); // use the default Constructor co = c. getConstructor (null); Object obj = co. newInstance (); // Method to obtain the object m = c. getMethod (methodName, null); // call the method m of the object. invoke (obj, null );}}

In this way, you only need to modify the content in the file, and the obtained content will be automatically obtained in the code.

I am the dividing line of tiantiao

Source code: http://pan.baidu.com/s/1dD1Qx01

Java .zip


What is reflection in JAVA?

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. The proposal of this concept soon led to research on application reflectivity in the computer science field. It was first adopted by the design field of programming language, and has made achievements in Lisp and object-oriented aspects. LEAD/LEAD ++, OpenC ++, MetaXa, and OpenJava are reflection-based languages. Recently, reflection mechanisms have been applied to Windows, operating systems, and file systems.

Reflection itself is not a new concept. It may remind us of the concept of reflection in optics. Although computer science has given a new meaning to the concept of reflection, in terms of phenomena, they do have some similarities that help us understand. In computer science, reflection is a type of application that can be self-described and self-controlled. That is to say, this type of application uses a mechanism to describe and monitor its own behavior, and according to its own behavior status and results, adjusts or modifies the status and semantics of the behavior described by the application. We can see that, compared with the general reflection concept, reflection in the computer science field not only refers to reflection itself, but also measures taken to reflect the results. All systems that adopt reflection mechanisms (I .e. reflection Systems) want to make their implementations more open. It can be said that all systems implementing reflection mechanisms are open, but open systems do not necessarily adopt reflection mechanisms. Openness is a necessary condition for reflection systems. In general, the reflection system must meet both the open conditions and the cause of connection (Causally-connected ). The so-called cause connection refers to the situation where the changes in the self-description of the reflection system can be immediately reflected in the actual status and behavior at the underlying level of the system, and vice versa. Open connection and cause connection are two basic elements of the reflection system. 13700863760

In Java, reflection is a powerful tool. It allows you to create flexible code that can be configured during running without the need for source representative links between components. Reflection allows us to enable our program code to access the internal information of classes loaded into the JVM when writing and executing, rather than the code for class collaboration selected in the source code. This makes reflection a major tool for building flexible applications. However, it should be noted that, if improperly used, reflection costs are high.

Ii. Class reflection in Java:
Reflection is one of the characteristics of the Java programming language. It allows running Java programs to check themselves, or "self-Review", and can directly operate on internal properties of the program. This capability of Java may not be used in many practical applications, but it does not exist in other programming languages. For example, Pascal, C, or C ++ cannot obtain information related to function definitions in the program.

1. Detection class:

1.1 reflection's Working Mechanism

The following simple example shows how reflection works.

Import java. lang. reflect .*;
Public class DumpMethods {
Public static void main (String args []) {
Try {
Class c = Class. forName (args [0]);
Method m [] = c. getDeclaredMethods ();
For (int I = 0; I <m. length; I ++)
System. out. println (m [I]. toString ());
} Catch (Throwable e ){
System. err. println (e );
}
}
}

As shown in the following figure... the remaining full text>

Java reflection calls the private Method

Import java. lang. reflect. Method;
Public class ReflectDemo {
Public static void main (String [] args) throws Exception {
Class clazz = PackageClazz. class;
For (Method method: clazz. getDeclaredMethods ()){
If ("privilegedMethod". equals (method. getName ())){
Method. setAccessible (true );
Method. invoke (clazz. newInstance (), "ajaxfan ");
Break;
}
}
}
}
Class PackageClazz {
Private void privilegedMethod (String invokerName ){
System. out. printf ("congratulations % s! ", InvokerName );
}
}
Private methods are visible within the class. If they do not pass reflection, they cannot be accessed. This is controlled by java runtime.

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.