类的类getDeclaredField()方法 (Class class getDeclaredField() method)
getDeclaredField() method is available in java.lang package.
getDeclaredField()方法在java.lang包中可用。
getDeclaredField() method is used to return a Field objects that indicate the given declared field of the class or an interface denoted by this Class object.
getDeclaredField()方法用于返回一个Field对象,该对象指示给定的类的声明字段或由此Class对象表示的接口。
getDeclaredField() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
getDeclaredField()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
getDeclaredField() method may throw an exception at the time of returning a Field object.
在返回Field对象时, getDeclaredField()方法可能会引发异常。
- NoSuchFieldException: In this exception when a specifying field does not exists.NoSuchFieldException :在此异常中,当指定字段不存在时。
- SecurityException: In this exception it may raise when security manager exists.SecurityException :在此异常中,当安全管理器存在时可能会引发此异常。
- NullPointerException: In this exception when the given Field is null.NullPointerException :在此异常中,当给定的Field为null时。
Syntax:
句法:
public Field getDeclaredField (String field_name);
Parameter(s):
参数:
String field_name – represents the name of the field.
字符串field_name –代表字段名称。
Return value:
返回值:
The return type of this method is Field, it returns Field object of the given Field in this Class.
此方法的返回类型为Field ,它返回此类中给定Field的Field对象。
Example:
例:
// Java program to demonstrate the example
// of Field getDeclaredField (String field_name) method of Class
import java.lang.reflect.*;
public class GetDeclaredFieldOfClass {
public static void main(String[] args) throws Exception {
GetDeclaredFieldOfClass declare_field = new GetDeclaredFieldOfClass();
// Get Class
Class cl = declare_field.getClass();
// By using getDeclaredField() method is to get the field of
// the class
Field f = cl.getDeclaredField("i");
System.out.println("Declared Field: " + f.toString());
}
// Private Constructors
private GetDeclaredFieldOfClass() {
System.out.println("We are in private constructor");
}
// Public Constructors
public GetDeclaredFieldOfClass(int i) {
this.i = i;
}
int i = 100;
}
Output
输出量
We are in private constructor
Declared Field: int GetDeclaredFieldOfClass.i
翻译自: https://www.includehelp.com/java/class-class-getdeclaredfield-method-with-example.aspx