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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。