The field is similar to the previous construction method and behavior method;
Package javainvokefiled;
Import Java.lang.reflect.Field;
/**
* Reflection Get Field
* @author Administrator
*
*/
Class filed{
public String name;
private int age;
private int number;
public String password;
Public Filed () {
}
}
public class Invokefiled {
/**
* Get the field method and the previous fetch constructor and method are very similar. Getfileds (): Gets all public-decorated fields and field rules that inherit from the parent class are similar to getting constructs and methods
* @param args
* @throws Exception
*/
public static void Main (string[] args) throws Exception {
Class Claz = Filed.class;
Class claz1=class.forname ("javainvokefiled.filed");
Field[] fields= claz.getfields ();
for (Field field:fields) {
System.out.println ("Get all public and inherited fields" +field);
}
Field[] Fieldsdecrs=claz.getdeclaredfields ();
for (Field Fielddecr:fieldsdecrs) {
System.out.println ("Get all fields including private/public, but do not include inherited fields" +FIELDDECR);
}
/* Get the specified field: Parameter pass field name * *
Field Field1=claz.getfield ("name");
System.out.println ("Get the specified public field" +field1);
/* Get the specified private field/*
Field FIELDP = Claz.getdeclaredfield ("number");
System.out.println ("Get the specified private field:" +FIELDP);
/**
* Set value for field: setxxx (obj, base type data) base type field set value; set (obj, reference type data) reference type set value obj as the underlying object of the field if it is a static field then obj can be null
*/
/* Set value for field/*
Field1.set (Claz.newinstance (), "Zhang Fei");
System.out.println (Field1.get (Claz.newinstance ()));
/* Set value for private field/*
Fieldp.setaccessible (TRUE);
Fieldp.setint (Claz.newinstance (), 12);
System.out.println (Fieldp.getint (Claz.newinstance ()));
/**
* Get field value: GetXXX (obj) get (obj) obj can be null if field is static decorated
*/
/* Get the value of the private static field/*
Field fieldd = Claz.getdeclaredfield ("str");
Fieldd.setaccessible (TRUE);
SYSTEM.OUT.PRINTLN (Fieldd.get (NULL) + "private static reference type");
/* Gets the value of the private field * *
Field fieldnum=claz.getdeclaredfield ("num");
Fieldnum.setaccessible (TRUE);
System.out.println (Fieldnum.getint (Claz.newinstance ()) + "private basic type");
}
}