Little Monsters Java Reflection Technology wait for you to hit

Source: Internet
Author: User
Tags instance method

Java reflection Technology, Java is the difficulty, but also the evolution of the programmer must play the small monster, here according to the Java API to study the Java reflection technology.

Class Fields Methods

Please recall the definition of Java class first.

First, what is reflection

What is reflection? Baidu Encyclopedia This definition: the Java reflection mechanism is in the running state, for any class, can know all the properties and methods of the class, for any one object, can call any of its methods and properties This dynamic acquisition of object information and the ability to dynamically invoke object methods is known as the reflection mechanism of the Java language.
As you can understand, when you were a child, there was wood and played flat mirror, in the sun, inclined flat mirror the sun to the dark place, or to someone's eyes? This is the reflection. In Java, reflection is the use of a demon mirror, to hide in the Java class can not see the ghosts and goblins to find out. Because of the encapsulation mechanism of the class, some properties and methods, we
cannot be viewed and used, it can be invoked dynamically using the reflection mechanism.
second, what does reflection do
1, at run time to determine the class of any object;
2, the object of constructing any class at run time;
3, at run time to judge any one class has the member variables and methods;
4, the method of invoking any object at run time;
5, generate dynamic agent.
To put it simply, we want to use a method that does not provide a class for an interface in the API. The simple point is that class A has a method A, but it is not provided in the API, we want to use it, it can be called by reflection technology, or Class A has a property B, we want to use, or can be implemented with reflection. Another function is to let us understand the structure of the whole class.
third, reflective knowledge points
1. Instantiation of class
In Java, each class has a corresponding class object. That is, when we write a class, after the compilation is complete, in the generated. class file, a class object is generated that represents the type information for this class.
Three ways to get the class object:
A, Object.getclass
Example: String str = "I love You";
Class C = Str.getclass ();

B, Class.forName ("ClassName")

Example: String className = "java.lang.String";
Class C = class.forname (ClassName);

C, Object.class
Example: Class c = string.class;
D, C.getsuperclass ();
Example: Class c = string.class;
Class s = C.getsupreclass ();
2. Class properties and Methods
If you just want to quickly use the Java reflection mechanism, please skip this section and go directly to the 3rd section to see the example.
A, Method summary (this is the Java API document excerpt from all the methods, if you feel cumbersome to skip this section, directly see my Summary of common methods (see B))
<U> class<? Extends u>
Assubclass (class<u> clazz)
Casts the class object to represent a subclass of the class represented by the specified class object.
T cast (Object obj)
Casts an object to the class or interface represented by this class object.
Boolean desiredassertionstatus ()
If the class is to be initialized when this method is called, the assertion state that will be assigned to the class is returned.
Static class<?> forname (String className)
Returns the class object associated with the classes or interfaces with the given string name.
Static class<?> forname (String name, Boolean initialize, ClassLoader loader)
Returns the class object associated with the classes or interfaces with the given string name, using the given class loader.
<a extends Annotation> A
Getannotation (class<a> annotationclass)
If there is a comment of the specified type for the element, the comments are returned, otherwise null is returned.
Annotation[] Getannotations ()
Returns all comments that exist on this element.
String Getcanonicalname ()
Returns the canonical name of the underlying class as defined in Java Language specification.
Class[] Getclasses ()
Returns an array containing some class objects that represent all public classes and interfaces that belong to the members of the class represented by this class object, including those inherited from the superclass and public classes, and public classes and interface members declared through the class.
ClassLoader getClassLoader ()
Returns the class loader for this class.
Class<?> Getcomponenttype ()
Returns the Class that represents the array component type.
Constructor<t> getconstructor (Class ... parametertypes)
Returns a Constructor object that reflects the specified public construction method for the class represented by this class object.
Constructor[] GetConstructors ()
Returns an array that contains some Constructor objects that reflect all the public constructor methods of the class represented by this class object.
Annotation[] Getdeclaredannotations ()
Returns all comments that exist directly on this element.
Class[] Getdeclaredclasses ()
Returns an array of class objects that reflect all classes and interfaces that declare members of the class represented by this class object, including public, protected, default (package) access, and private classes and interfaces declared by the class, but do not include inherited classes and interfaces.
Constructor<t> getdeclaredconstructor (Class ... parametertypes)
Returns a Constructor object that reflects the specified construction method for the class or interface represented by this class object.
Constructor[] Getdeclaredconstructors ()
Returns an array of Constructor objects that reflect all of the constructor methods for the class declaration represented by this class object.
Field Getdeclaredfield (String name)
Returns a Field object that reflects the specified declared field of the class or interface represented by this class object.
Field[] Getdeclaredfields ()
Returns an array of field objects that reflect all the fields declared by the class or interface represented by this class object, including public, protected, default (package) access, and private fields, but excluding inherited fields.
Method Getdeclaredmethod (String name, Class ... parametertypes)
Returns a method object that reflects the specified declared method of the class or interface represented by this class object.
Method[] Getdeclaredmethods ()
Returns an array of method objects that reflect all methods of the class or interface declaration represented by this class object, including public, protected, default (package) access, and private methods, but not inherited methods.
Class<?> Getdeclaringclass ()
If the class or interface represented by this class object is a member of another class, the returned class object represents the declared class of the object.
Class<?> Getenclosingclass ()
Returns an immediate enclosing class for the underlying class.
Constructor<?> Getenclosingconstructor ()
If the class object represents a local or anonymous class in a constructed method, the Constructor object is returned, which represents an immediate enclosing construction method for the underlying class.
Method Getenclosingmethod ()
If this class object represents a local or anonymous class in a method, the method object is returned, which represents an immediate closure of the underlying class.
T[] Getenumconstants ()
If this class object does not represent an enumeration type, the element of the enumeration class or null is returned.
Field GetField (String name)
Returns a Field object that reflects the specified public member field of the class or interface represented by this class object.
Field[] GetFields ()
Returns an array containing some field objects that reflect all accessible public fields for the class or interface represented by this class object.
Type[] Getgenericinterfaces ()
Returns a type that represents some interfaces that are directly implemented by the class or interface represented by the object.
Type Getgenericsuperclass ()
Returns the type of the direct superclass that represents the entity (class, interface, base type, or void) represented by this class.
Class[] Getinterfaces ()
Determines the interface that this object represents for the implementation of the class or interface.
Method GetMethod (String name, Class ... parametertypes)
Returns a method object that reflects the specified public member methods for the class or interface represented by this class object.
Method[] GetMethods ()
Returns an array containing some method objects that reflect the public member method for the class or interface represented by this class object, including those declared by the class or interface, and those inherited from the superclass and the hyper-interface.
int getmodifiers ()
Returns the Java language modifier for this class or interface, encoded in integers.
String GetName ()
Returns the name of the entity (class, interface, array class, base type, or void) represented by this class object as a String.
Package Getpackage ()
Gets the package for this class.
Protectiondomain Getprotectiondomain ()
Returns the Protectiondomain of the class.
URL getresource (String name)
Finds a resource with the given name.
InputStream getResourceAsStream (String name)
Finds a resource with the given name.
Object[] Getsigners ()
Gets the markup for this class.
String Getsimplename ()
Returns the short name of the underlying class given in the source code.
class<? Super T> Getsuperclass ()
Returns the class of the superclass representing the entity (class, interface, base type, or void) represented by this class.
Typevariable<class<t>>[] Gettypeparameters ()
Returns an array of Typevariable objects in declaration order that represent the type variables declared with the general declaration represented by this Genericdeclaration object.
Boolean isannotation ()
Returns true if this Class object represents a comment type.
Boolean isannotationpresent (class<? extends annotation> Annotationclass)
Returns true if a comment of the specified type exists on this element, otherwise false is returned.
Boolean Isanonymousclass ()
Returns True when and only if the underlying class is an anonymous class.
Boolean IsArray ()
Determines whether this class object represents an array class.
Boolean IsAssignableFrom (class<?> CLS)
Determines whether the class or interface represented by this class object is the same as the class or interface represented by the specified class parameter, or whether it is a superclass or a hyper-interface.
Boolean isenum ()
Returns True when and only if the class is declared as an enumeration in source code.
Boolean isinstance (Object obj)
Determines whether the specified object is compatible with the value represented by this Class.
Boolean isinterface ()
Determines whether the specified Class object represents an interface.
Boolean Islocalclass ()
Returns True when and only if the underlying class is a local class.
Boolean Ismemberclass ()
Returns True when and only if the underlying class is a member class.
Boolean isprimitive ()
Determines whether the specified Class object represents a base type.
Boolean issynthetic ()
Returns true if this class is a composite class, otherwise false.
T newinstance ()
Creates a new instance of the class represented by this class object.
String toString ()
Converts an object to a string.
B. Common methods
Public String GetName ()
Returns the name of the entity (class, interface, array class, base type, or void) represented by this class object as a String.

Public ClassLoader getClassLoader ()
Returns the class loader for this class. Some implementations may use NULL to represent the bootstrap class loader. If the class is loaded by the Boot class loader, this method returns Null in such implementations.

Public Package Getpackage ()
Gets the package for this class. The class loader for this class is used to find the package. If the class is loaded by the bootstrap ClassLoader, search the collection of packages loaded from CLASSPATH to find the package for that class. Returns NULL if all package objects are not loaded with the class loader for the class.

Public field[] GetFields () throws SecurityException
Returns an array containing some field objects that reflect all accessible public fields for the class or interface represented by this class object. The elements in the returned array are not sorted or in any particular order. This method returns an array of length 0 if the class or interface does not have an accessible public field, or represents an array class, a base type, or void.
In particular, if the class object represents a class, this method returns the public fields of the class and all of its superclass. If the Class object represents an interface, this method returns the public fields for that interface and all of its hyper-interfaces.
The method does not reflect the implicit length field of the array class. The user code should manipulate the array using the method of the array class.

Public method[] GetMethods () throws SecurityException
Returns an array containing some method objects that reflect the public member method for the class or interface represented by this class object, including those declared by the class or interface, and those inherited from the superclass and the hyper-interface. The array class returns all the (public) member methods inherited from the Object class. The elements in the returned array are not sorted or in any particular order. If this class object represents a class or interface that does not have a public member method, or represents a base type or void, this method returns an array of length 0.
The class initialization method <clinit> is not included in the returned array. If a class declares multiple public member methods with the same parameter type, they are included in the returned array.

Public Field GetField (String name) throws Nosuchfieldexception, SecurityException
Returns a Field object that reflects the specified public member field of the class or interface represented by this class object. The name parameter is a String that specifies the short name of the field you want.

Public Method GetMethod (String name, Class ... parametertypes) throws Nosuchmethodexception, SecurityException
Returns a method object that reflects the specified public member methods for the class or interface represented by this class object. The name parameter is a String that specifies the short name of the method you want. The Parametertypes parameter is an array of Class objects that identify the method form parameter type in the order in which they are declared. If parametertypes is null, it is processed by an empty array.

Public field[] Getdeclaredfields () throws SecurityException
Returns an array of field objects that reflect all the fields declared by the class or interface represented by this class object, including public, protected, default (package) access, and private fields, but excluding inherited fields. The elements in the returned array are not sorted or in any particular order. If the class or interface does not declare any fields, or if this class object represents a base type, an array class, or void, this method returns an array of length 0.

Public method[] Getdeclaredmethods () throws SecurityException
Returns an array of method objects that reflect all methods of the class or interface declaration represented by this class object, including public, protected, default (package) access, and private methods, but not inherited methods. The elements in the returned array are not sorted or in any particular order. If the class or interface does not declare any methods, or if this class object represents a base type, an array class, or void, this method returns an array of length 0. The class initialization method <clinit> is not included in the returned array. If the class declares multiple public member methods with the same parameter type, they are included in the returned array.

3. Method class and Field class
A, Method
The method provides information about a single method on a class or interface (and how to access it). The method that is reflected may be a class method or an instance method, including an abstract method.
Method allows extended conversions to match the formal parameters of the underlying method to be invoked, but throws a illegalargumentexception if a narrowing conversion is to be made.

Public String GetName ()
Returns the name of the method represented by this method object as a String.

public object invoke (Object obj, Object ... args) throws Illegalaccessexception, IllegalArgumentException, InvocationTargetException
Invokes the underlying method represented by this method object on the specified object with the specified argument. Individual parameters are automatically unpacked to match the basic parameters, and both the basic and reference parameters are subject to the method invocation transformation.
If the underlying method is static, the specified obj parameter can be ignored. The parameter can be null.
If the underlying method requires a shape parameter of 0, the supplied args array can be 0 or null in length.
If the underlying method is an instance method, it is called using the dynamic method lookup, which is recorded in the 15.12.4.4 section of Java Language specification, Second Edition, and should be done in the case of overrides based on the runtime type of the target object.
If the underlying method is static and the class declaring the method has not been initialized, it will be initialized.
If the method completes normally, the value returned by the method is returned to the caller, and if the value is a base type, it is first wrapped appropriately in the object. However, if the type of the value is a set of basic types, the array element is not wrapped in the object, in other words, an array of the base type is returned. If the underlying method return type is void, the call returns NULL.

B, Field
field provides information about a single field of a class or interface, as well as its dynamic access rights. The reflected field may be a class (static) field or an instance field.
Array allows extended conversions during a get or set access operation, but throws a illegalargumentexception if a narrowing conversion occurs.

Public String GetName ()
Returns the name of the field represented by this Field object.

There are many other methods of method and field classes that are not described here and can be viewed in the API documentation.
Isn't it a headache to see? It doesn't matter, this is just understanding, for smart you, look at the following example to fully understand the Java reflection mechanism is what.

Iv. How to use reflection
Test class
public class Programmer {
private String name;
private int age;
Private String technology;

private String Program (string s) {
return this.name + "in use" + This.technology + "write" + S;
}

Public Programmer () {

}

Public Programmer (string name, int age, string technology) {
Super ();
THIS.name = name;
This.age = age;
This.technology = technology;
}

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}

public int getage () {
return age;
}

public void Setage (int.) {
This.age = age;
}

Public String gettechnology () {
return technology;
}

public void Settechnology (String technology) {
This.technology = technology;
}
}

Test
public static void Main (string[] args) throws Nosuchmethodexception,
SecurityException, Illegalaccessexception,
IllegalArgumentException, InvocationTargetException,
nosuchfieldexception {
TODO auto-generated Method Stub
Programmer Programmer = new Programmer ("Zhaicaixiansheng", "%", "Java");
Class C = Programmer.getclass ();//Get Class object instance
method = C.getdeclaredmethod ("program",
New class[] {string.class});//The first parameter is the method name and the second is the Class of the desired parameter type. Get the method defined by programmer (any method can)
if (Method! = null) {
Method.setaccessible (TRUE);//Set to True
String info = (string) method.invoke (programmer,
New string[] {"Run bar Brother"});//Use method, the first parameter is the object name, the second is the parameter
SYSTEM.OUT.PRINTLN (info);
}

Field field = C.getdeclaredfield ("name");
if (field! = null) {
Field.setaccessible (TRUE);
Field.set (programmer, "Mr. Cai");
}

String info = (string) method.invoke (programmer,
New string[] {"Run it Brother"});
SYSTEM.OUT.PRINTLN (info);
}

v. Advantages and disadvantages of reflection
Advantages: Increase the flexibility of the program, dynamic call, enrich the program interface and so on.
Disadvantages: The encapsulation characteristic of destroying the program;
vi. attention and summary
Note: Although reflection technology can increase the flexibility of the program, you can dynamically invoke methods and properties that are not visible in the class, but you cannot rely too much on reflection, which can result in confusing program structures, decreased code readability, and poor security.
Summary: Programming is actually very easy, where not to search where.
I Love programming. I Love you.

Little Monsters Java Reflection Technology wait for you to call

Related Article

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.