Java Reflection Basics (ii) Use of--fileds objects __java

Source: Internet
Author: User
Tags modifier modifiers reflection volatile

Before we say filed, let's take a look at the member interface. An interface java.lang.reflect.Member is defined in the reflection. Java.lang.reflect.Field, Java.lang.reflect.Method, and Java.lang.reflect.Constructor. Implements the interface. We'll introduce these classes in the next section. For each member, we'll introduce the relevant APIs to get and manipulate that member. Each concept we use sample code and sample output instructions.

1. Get the Type of field (fields)

A filed can be a basic data type or a reference type. There are eight basic data types in Java: Boolean, Byte, short, int, long, char, float, A reference type can enable any direct or indirect inheritance of java.lang.Object interfaces, arrays, or enumerations.

The Filedspy sample class implements the printing of field types and generics contained in a given class's binary file.

Import Java.lang.reflect.Field;
Import java.util.List;

public class Fieldspy<t> {public
    boolean[][] B = {{false, false}, {True, true}};
    Public String Name  = "Alice";
    Public list<integer> List;
    Public T-Val;

    public static void Main (String ... args) {
	try {
	    class<?> c = class.forname (Args[0]);
	    Field f = C.getfield (args[1]);
	    System.out.format ("Type:%s%n", F.gettype ());
	    System.out.format ("GenericType:%s%n", F.getgenerictype ());

        Production code should handle this exceptions more gracefully
	} catch (ClassNotFoundException x) {
	    x.printst Acktrace ();
	} catch (Nosuchfieldexception x) {
	    x.printstacktrace ();}}}

Instance output:

$ java fieldspy fieldspy b
type:class [[Z
generictype:class [[z
$ java fieldspy fieldspy name
Type:clas s java.lang.String
generictype:class java.lang.String
$ java fieldspy fieldspy list
type:interface Java.util.List
generictype:java.util.list<java.lang.integer>
$ java fieldspy fieldspy val
Type: Class Java.lang.Object
Generictype:t

The type of field B is a two-dimensional, Boolean array.

The type of the field Val is identified as Java.lang.Object. Because generics are implemented in the process of compiling, the information related to generics is replaced with related classes. So here is java.lang.Object.

2. Get and resolve field modifiers (Filed Modifier)

There are several field modifiers in Java: Access control modifiers: public, protected, and private runtime Domain Admin modifiers: transient and volatile control An instance modifier: Static forbidden value modifier: FI nal annotation

Method Field.getmodifiers () can be used to obtain a field modifier that is represented as an integer. These are defined in Java.lang.reflect.Modifier.

The example class Fieldmodifierspy describes how to search for fields that are decorated by a specified modifier in a class.

Import Java.lang.reflect.Field;
Import Java.lang.reflect.Modifier;

Import static java.lang.System.out;
    Enum Spy {black, white} public class Fieldmodifierspy {volatile int share;
    int instance;
	    Class Inner {} public static void Main (String ... args) {try {class<?> c = class.forname (Args[0]);
	    int searchmods = 0x0;
	    for (int i = 1; i < args.length i++) {searchmods |= modifierfromstring (args[i));
	    } field[] Flds = C.getdeclaredfields (); Out.format ("Fields in Class '%s ' containing modifiers:%s%n", C.getname (), Modifier.tostring (searchmods
	    ));
	    Boolean found = false;
		for (Field f:flds) {int foundmods = F.getmodifiers (); Require all of the requested modifiers to is present if (Foundmods & searchmods) = = searchmods) {Out.form
		    at ("%-8s [synthetic=%-5b enum_constant=%-5b]%n", F.getname (), f.issynthetic (), f.isenumconstant ());
		Found = true;

	}
	    }    if (!found) {Out.format ("No matching fields%n"); }//Production code should handle this exception more gracefully} catch (ClassNotFoundException x) {X.PR
	Intstacktrace ();
	The private static int modifierfromstring (String s) {int m = 0x0;
	if ("Public". Equals (s)) m |= modifier.public;
	else if ("protected". Equals (s)) m |= modifier.protected;
	else if ("Private". Equals (s)) m |= modifier.private;
	else if ("Static". Equals (s)) m |= modifier.static;
	else if ("final". Equals (s)) m |= modifier.final;
	else if ("transient". Equals (s)) m |= modifier.transient;
	else if ("volatile". Equals (s)) m |= Modifier.volatile;
    return m;
 }
}

Sample output:

$ java fieldmodifierspy fieldmodifierspy volatile
Fields in Class ' Fieldmodifierspy ' containing modifiers:  Volatile
share    [Synthetic=false Enum_constant=false]

$ java fieldmodifierspy Spy public
Fields in Class ' Spy ' containing modifiers: public black    [synthetic=false enum_constant=true  ]
White    [Synthetic=false enum_constant=true  ]

$ java fieldmodifierspy fieldmodifierspy\ $Inner final
Fields in Class ' Fieldmodifierspy$inner ' containing modifiers:  final
this$0   [Synthetic=true  Enum_constant=false]

$ java fieldmodifierspy Spy private static final
Fields in Class ' Spy ' containing modifier S:  private static final
$VALUES  [synthetic=true  Enum_constant=false]

Notice that some of the fields are displayed, although they are not defined in the source code of the class. The reason is that the compiler will automatically generate some fields (synthetic fields: these fields refer to a user-displayed declaration, but are synthesized by the compiler at compile time). If you want to know whether a field is synthetic (synthetic), you have also used the Field.issynthetic () method. The collection of synthetic fields is dependent on the compiler. However, the common use of this$0 represents the outermost encapsulated class in the inner class. Using $ in an enumeration The values class defines the implicit static method values (). The name of the composite class is not always the same, and different compilers may have different names. and not all synthetic fields are declared public.

Because field implements the Java.lang.reflect.AnnotatedElement interface, So we can also use Java.lang.annotation.RetentionPolicy.RUNTIME to get run-time annotations. For a specific example, see examining Class modifiers and Types.

3. Gets and sets the field value.

Give us a class instance where we can use reflection to modify the value of a field. This is often used in an environment where the values of the field cannot be modified in the usual way. Because such operations usually violate the design intent of the class, this should be used sparingly.

The book sample class shows how to set the field values for long, array, and enum types. Other types of corresponding methods, reference Java API.

Import Java.lang.reflect.Field;
Import Java.util.Arrays;

Import static java.lang.System.out;
    Enum Tweedle {DEE, DUM} public class Book {public long chapters = 0;
    Public string[] characters = {"Alice", "White Rabbit"};

    Public Tweedle twin = Tweedle.dee;
	public static void Main (String ... args) {Book book = new book ();

	String FMT = "%6s:%-12s =%s%n";

	    try {class<?> c = book.getclass ();
	    Field chap = C.getdeclaredfield ("chapters");
  	    Out.format (FMT, "before", "chapters", Book.chapters);
	    Chap.setlong (book, 12);

	    Out.format (FMT, "after", "chapters", Chap.getlong (book));
	    Field chars = C.getdeclaredfield ("characters");
	    Out.format (FMT, "before", "characters", Arrays.aslist (book.characters));
	    String[] Newchars = {"Queen", "King"};
	    Chars.set (book, newchars);

	    Out.format (FMT, "after", "Characters", Arrays.aslist (book.characters));
	    Field t = C.getdeclaredfield ("twin"); OUT.FORMAT (FMT, "before", "twin", Book.twin);
	    T.set (book, tweedle.dum);

        Out.format (FMT, "after", "Twin", T.get (book)); Production code should handle this exceptions more gracefully} catch (Nosuchfieldexception x) {X.printstacktra
	CE ();
	catch (Illegalaccessexception x) {x.printstacktrace ();
 }
    }
}

Sample output:

$ java Book
before:  chapters     = 0 after
 :  chapters     =
before:  characters   = [ Alice, White Rabbit] after
 :  characters   = [Queen, King]
before:  twin         = DEE after
 :  Twin         = DUM
Note: It often takes a lot of action to set the value of a field by reflection. Because many additional operations must be performed, for example, to detect the accessibility of the data. But from a run-time perspective, the results are the same. Because all operations are treated as a yard operation, it is equivalent to directly modifying the value of the variable.
E: Using reflection can cause some run-time optimizations to fail. For example, the following code is easily optimized by Java virtual machines:
int x = 1;
x = 2;
x = 3;

However, if you use reflection, you use field.set* (), which is an optimization failure.

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.