Java reflection and java reflection

Source: Internet
Author: User

Java reflection and java reflection

You have self-knowledge. I will not study immediately. Forget to complete immediately.

Because my reflection was learned a year ago. Many things have been forgotten. Yesterday, Alibaba submitted a reflection during the interview. I only vaguely remember Class. forName, getMethod, and newInstant.

In fact, I think there is a lot of internal knowledge about java. Spring I know is reflection. I know exactly what to do. However, if I leave Eclipse and intellij idea, I cannot leave empty handwritten code without API documentation.

Next, I will briefly review reflection. Spring's AOP is object-oriented programming. I like Apis. Either way. Generally, this framework configures beans in spring. xml. Currently, many programs do not like configuration. In the form of annotations, annotations such as @ Service, @ Controller, and @ Resource are preferred. Achieve 0 configuration through annotation combination. But the general idea is based on reflection.

For example, we first write a simple Pojo

public class Student{private String name;public Student(){}public Student(String name){this.name = name;}public String getName(){return name;}public void setName(String name){this.name = name;}}
Then we will write another test class.

Import java. lang. reflect. constructor; import java. lang. reflect. method; public class test {/*** @ param args */public static void main (String [] args) throws Exception {Class cls_1 = Class. forName ("Student"); // obtain the Class by name, which usually requires a prefix of the package name. Class cls_2 = Student. class; // directly pass. the class file obtains the Classif (cls_1.equals (cls_2) System. out. println ("this is sample Class"); Student stu = (Student) cls_1.newInstance (); // get the object through the no-argument constructor new, constructor <Student> SC = cls_1.getConstructor (String. class); // if the class does not contain a constructor without parameters, an exception is thrown. In this case, you must first obtain the specified constructor Student stu2 = SC. newInstance ("haha"); System. out. println (stu2.getName (); Method me1 = cls_1.getMethod ("setName", String. class); // obtain Method me1.invoke (stu, "jungle") by name + parameter type class; // call the specified parameter System of the specified instance. out. println (stu. getName ());}}
Running result

this is sample Classjunglehaha

Is it easy. In fact, I think there are a lot of linguistics that I can't help but forget. But you just need to understand the API documentation and principles. In addition to the time when the Code was written by a Dos punching machine in the 80 s and 1990s s. There are so many java things. Often Remember to forget to query documents. It is better to use resources such as StackOverflow. No. I am a shipping 233333


Java reflection mechanism

Import java. lang. reflect. InvocationTargetException;
Import java. lang. reflect. Method;

Public class Admin {
Public Admin (){

}
Private String id = "";

Public String getId (){
System. out. print (id );
Return id;
}
Public void setId (String id ){
This. id = id;
}

Public static void main (String [] args)
Throws ClassNotFoundException, InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

String str = "com. spring. event. Admin ";
Class c = Class. forName (str );
Object obj = c. newInstance ();

// Set the attribute value here
Method m = c. getMethod ("setId", new Class [] {Class. forName ("java. lang. String ")});
M. invoke (obj, new Object [] {"penghao122 "});

// Obtain the attribute value in
M = c. getMethod ("getId", new Class [] {});
M. invoke (obj, new Object [] {});

}

}

Import java. lang. reflect. InvocationTargetException;
Import java. lang. reflect. Method;

Public class Admin {
Public Admin (){

}
Private String id = "";

Public String getId (){
System. out. print (id );
Return id;
}
Public void setId (String id ){
This. id = id;
}

Public static void main (String [] args)
Throws ClassNotFoundException, InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

String str = "com. spring. event. Admin ";
Class c = Class. forName (str );
Object... the remaining full text>

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>

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.