java.lang.reflect.Field的getDeclaringClass()方法用于获取Class对象,该对象声明此Field对象表示的字段。如果存在Field对象,并且我们想要获取类对象,则可以使用此方法获取该类对象。
用法:
public Class<T> getDeclaringClass()
参数:此方法不接受任何内容。
返回值:此方法返回一个对象,该对象表示基础成员的声明类。
以下示例程序旨在说明getDeclaringClass()方法:
示例1:
// Java program to demonstrate the above method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws NoSuchFieldException,
SecurityException
{
// Get the value field object
Field field
= User.class
.getField("identificationChar");
// get the declaring class object
Class declaringClass
= field.getDeclaringClass();
// print result
System.out.println("Declaring Class"
+ " for Field Object: "
+ declaringClass);
}
}
// sample User class
class User {
// static char values
public static char identificationChar = 'E';
public static char selectionChar = 'A';
public static String name = "Aman";
// getter and setter methods
public static char getIdentificationChar()
{
return identificationChar;
}
public static void
setIdentificationChar(char identificationChar)
{
User.identificationChar = identificationChar;
}
public static char getSelectionChar()
{
return selectionChar;
}
public static void
setSelectionChar(char selectionChar)
{
User.selectionChar = selectionChar;
}
public static String getName()
{
return name;
}
public static void setName(String name)
{
User.name = name;
}
}
输出:
Declaring Class for Field Object: class User
示例2:
// Java program to demonstrate the above method
import java.lang.reflect.Field;
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws NoSuchFieldException,
SecurityException
{
// Get the value field object
Field field
= Alphabets.class.getField("value");
// get the declaring class object
Class declaringClass
= field.getDeclaringClass();
// print result
System.out.println("Declaring Class: "
+ declaringClass);
}
// Alphabets class
static class Alphabets {
// char field
public static char value = 'Q';
// getter and setter methods
public static char getValue()
{
return value;
}
public static void setValue(char value)
{
Alphabets.value = value;
}
}
}
输出:
Declaring Class: class GFG$Alphabets
参考文献: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getDeclaringClass–
相关用法
- Java Class getDeclaringClass()用法及代码示例
- Java Constructor getDeclaringClass()用法及代码示例
- Java Field get()用法及代码示例
- Java Field set()用法及代码示例
- Java Field isEnumConstant()用法及代码示例
- Java Field getAnnotatedType()用法及代码示例
- Java Field toString()用法及代码示例
- Java Field setBoolean()用法及代码示例
- Java Field getInt()用法及代码示例
- Java Field getGenericType()用法及代码示例
- Java Field getLong()用法及代码示例
- Java Field hashCode()用法及代码示例
- Java Field getType()用法及代码示例
- Java Field getModifiers()用法及代码示例
- Java Field getDeclaredAnnotations()用法及代码示例
注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 Field getDeclaringClass() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。