java getfield_Java类类getField方法及示例

时间:2025-01-25 08:05:07

java getfield

类的类getField()方法 (Class class getField() method)

  • getField() method is available in package.

    getField()方法在包中可用。

  • getField() method is used to return a Field objects that indicate the given public member field of the class or an interface denoted by this Class object.

    getField()方法用于返回一个Field对象,该对象指示该类的给定公共成员字段或由此Class对象表示的接口。

  • getField() 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.

    getField()方法是一个非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。

  • getField() method may throw an exception at the time of returning a Field object.

    getField()方法在返回Field对象时可能会引发异常。

    • NoSuchFieldException: In this exception when a specifying field does not exist.NoSuchFieldException :在此异常中,当指定字段不存在时。
    • SecurityException: In this exception, it may raise when the security manager exists.SecurityException :在此异常中,当安全管理器存在时可能会引发此异常。
    • NullPointerException: In this exception when the given field is null.NullPointerException :在此异常中,给定字段为null。

Syntax:

句法:

    public Field getField (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 getField (String field_name) method of Class 

import .*;

public class GetFieldOfClass {
    public static void main(String[] args) throws Exception {
        GetFieldOfClass field = new GetFieldOfClass();

        // Get Class
        Class cl = ();

        // By using getField() method is to get the public field of
        // the class 
        Field f = ("i");
        ("Field: " + ());
    }

    // Private Constructors
    private GetFieldOfClass() {
        ("We are in private constructor");
    }

    // Public Constructors
    public GetFieldOfClass(int i) {
         = i;
    }

    public int i = 100;
}

Output

输出量

We are in private constructor
Field: public int 


翻译自: /java/

java getfield