Java类类getDeclaredField()方法及示例

类的类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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值