Parsing the field class and method class in Java _java

Source: Internet
Author: User
Tags reflection wrapper

Field class
the field class defines methods that you can use to query the type of a field and to set or read the value of a field. Combine these methods with the inherited member method. It allows us to find all the information about the field declaration and to manipulate the fields of a particular object or class.

The Getgenerictype method returns an instance of type that represents the declared type of the field. For trivial types like string or int, this method returns the class objects associated with them, such as String.class and Int.classo for parameterized types like List < Stri ng>. The method returns an instance of Parameterizedrype, for example, for a type such as T, which returns a typevariable instance.

The left-GetType method returns the class object of the type of the field. For trivial types, the method behaves the same as the Getgenerictype method. If the declared type of the field is a parameterized type, the GetType method returns the class object for the erase of the parameterized type, that is, the class object of the original type. For example, for objects declared as List < Stri ng>, GetType will return to the Li St. class. If the declared type of the field is a type variable, the GetType method returns the class object corresponding to the erase of the type variable. For example, suppose you have a class foo<, and for a field that is declared as type T, get D ype will return object.

Class object. If Foo is declared foo< under extends number, then get under ype will return Number.class.

We can use the Isenumconstant method to query whether a field is an enumerated constant, or you can use the get and set methods to obtain and set the value of a field. These methods that accept the object argument and return obj ECT values have a common form, as well as some more specific forms that can directly handle the basic types. All of these methods accept an argument to specify the object to manipulate. For static fields, this object argument is ignored, so you can also set it at this time

to null. The following method prints the value of the short field of an object:

public static void Printshortfield (Object o, String name)

throws Nosuchfieldexception,illegalaccessexception

{

Field field=o.getclass (). GetField (name);

Short value= (short) field.get (o);

System.out.println (value);

The return value of the Get method can be any object referenced by the field, and if the field is a base type, the method returns the appropriate type of wrapper class object. For our Hort field, the Get method returns an object of type short containing the value of the field, and when it is assigned to the local variable value, the object value is automatically disassembled.

The use of Set methods is similar. The method of setting the short field to the supplied value might look like this:

public static Voi

Setshortfield (Object o,string Name,short nv)

throws Nosuchfieldexception,  Illegalaccessexception

Field Field=0.getclass (). GetField (name);

field. Set (O. nv);

Although set accepts arguments of type object, we can pass a short value directly and wrap it as a short type object with the wrapper transformation.

In the above method, if the domain of the specified object is inaccessible and the access control is enforced, a illegalaccessexception exception is thrown, and if the object being passed is different from the type of the field, Throws a IllegalArgumentException exception, and if the domain is non-static and the passed object reference is null, a NullPointerException exception is thrown, and accessing the static domain may require initialization of the class. So the method also throws a Exceptionininitializererror exception.

The field class also has a specific method for getting and setting the base type, for example, we can invoke Getprimitive7ype and set Primitive7ype on a Field object, where Primitive7ype is the basic type name (first-letter uppercase). The Get method can be used for the following statement:

Short Value=field.getshort (o);

The set method can be used for the following statement:

Field.setshort (O, NV);

You can avoid using wrapper class objects in statements declared in both of these ways.

The field class implements the Annotatedelement interface, so we can also query for fields like section 16.2

Annotations on the.

With the method described above, we can use a Field object as a way to manipulate arbitrary values, but we should try to avoid it. Because the Java language captures as many programming errors as possible during the compilation of a program, the less indirect methods that are used when we write code, such as the "ield object, can prevent more errors before compiling them into code. And, as we can see, in the previous code, the amount of energy we spend on reading code is obviously much greater than the fact that we're using the domain name directly in the normal syntax in order to know what's going to happen.

Final field

In general, setting a field that is declared final will cause the illegalaccessexception to be thrown
Exception, which is what we can expect, because the final field value is never changed. But there are special cases-for example, in custom deserialization (see 20.8.4), it makes sense to change the final field's value, and we can do this only by reflection on the instance field, provided that setaccessible is already called on the Field object (True )。 Note that it is not enough to successfully invoke Setaccessible (true), it must have been called.

This ability is provided for a highly-specific context and is not intended for general purposes, and we introduce it only to preserve the integrity of the content. If you break out of a particular context, such as custom deserialization, changing the value of the final field can result in unexpected and even disastrous consequences. Beyond these contexts, there is no guarantee that changes to the final field are visible. Even in such contexts, it is necessary to ensure that the security mechanism does not impede the execution of the code when using this technology code. The final field that changes the value to a constant (see 2.2.3) will cause the change to be invisible, unless the modification is done by using reflection.

Method class
the method class and the methods it inherits from the member class allow us to obtain complete information about the method declaration:

"Public type Getgenericreturntypeo: This method returns a type object of the return type of the target method. If the target method is declared to return void, the method returns the Void.classo

Public type[] Getgenericparametertypes (): This method returns an array of type objects of all parameter types of the target method, which are stored in the array in the order in which they are declared. If the target method does not have any parameters, the method returns an empty array.

. publ I c Type [] getgeneri caccepti ontypes Q: This method returns an array of type objects of all the exception types listed in the throws clause, which are stored in the array in the order in which they are declared.

If the target method does not declare any exceptions, the method returns an empty array.

Java also provides getreturntype,getparametertypes and Getexceptiontypes methods to return the CL as object instead of the type object. As with Field.gettype, parameterized types and type variables are represented by the corresponding class object of their erasure.

The method class implements the Annotatedelement, and we can query the annotations applied to methods as discussed in section 16.2. In addition, the method class provides getparameterannotations to provide access to the annotations that are used on method parameters. The Getparameterannotations method can return a annotation array in which each element of the outermost array corresponds to the parameter of the method, and if a parameter has no annotations, the method returns a annotation array of length 0 for this parameter. If the method object represents itself as a callout element, the Getdefaultvalue method returns an object that represents the default value of the element, or null if the method object itself is not a callout element or it does not have a default value. The method class also implements Genericdeclaration, so the Gettypeparameters method is defined, which returns an array of Typevariable objects. The method returns an empty array if the given method object does not represent a generic approach.

We can use the Isvarargs method to check whether a method object is a mutable element approach, and the I Sbridge method can be used to check whether it is a bridging method

The most interesting use of the method object is to invoke itself by reflection:

. public object Invoke (object Onthis,object...args) throws Illegalaccessexception,illegalargumentexception, Nvocation under Argetexception: This method invokes the method object definition on the Onthis object and sets the parameters of the invoked method with the args value. For non-static methods, the actual type of the onthis determines which implementation of the method will be invoked, and for the static method, Onthis is ignored and is usually set to null. The number of args values must be the same as the actual number of parameters of the invoked method, and the types of those values must all be assignable to the parameters of the invoked method; otherwise, we will get a llegalargumentexception exception. Note that the last parameter of the variable element method is an array, so we must populate the array with the "variable" argument that we actually want to pass. If we want to invoke a method that we do not have access to, the method throws a Illegalaccessexception exception. If the invoked method is not a method on the next his object, the method throws the worker Llegalargumentexcepti on exception. If onthis is null and Non-static, the method throws a no 1PointerException exception. If the method object represents a static method, and the class that declares the static method is still in the state to be initialized, it throws a Exceptionin Nitializererror exception. If the power is modulated, the invocationtargetexception exception is thrown by talking about Wanfa.

When we use the Invoke method, we can pass the basic type directly, or we can use the appropriate wrapper class. The type represented by the wrapper class must be assignable to the type of the argument declared by the method. We can use long,float or double to wrap an argument of type double, but you cannot wrap a long or float argument with a double, because double is not assignable to long or to the oat. As with Field.get, the object returned by the Invoke method is returned to the base type of the wrapper class that corresponds to them. If the method declares void, the Invoke method returns NULL,

To put it simply, when invoking a method with invoke, we can only use the legal parameter in the Java language

An argument with the same type and value. For example, the following call

Return Str.indexof (".", 8);

Reflection can be written in the following form:

Throwable fa are ure;

try{method

Indexm=string.class.

GetMethod ("index0f", string.class,int.class);

Return (Integer) Indexm.invoke (str, ",", 8);

}catch (nosuchmethodexception e) {

failure=e;

}catch (InvocationTargetException e) {

FA ure=e getcause ();

}catch (illegalaccessexception e) {

failure=e;

throw FA are ure;

Although the compiler's security checks for direct invocation, in the case of reflection, can only be done at runtime using invoke, the reflection based code does have a semantically equivalent security check with the code that is invoked directly. Access checks may be performed in a slightly different way-the security manager may deny access to a method in our package, even if we can call the method directly.

When we can use this form of invocation, we have good reason to avoid it. But it would be reasonable to use the Invoke or Get/set method when writing a debugger or other generic application that needs to interpret user input as an object operation. The method object can be used in some way as a pointer to methods in other languages, but we have better tools, especially interfaces, abstract classes, and nested classes, that can be used to deal with problems that are usually resolved in other languages with method pointers.

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.