Java Field getDeclaringClass()方法

java.lang.reflect.Field.getDeclaringClass()方法返回表示声明由此Field对象表示的字段的类或接口的Class对象。

1 语法

public Class<T> getDeclaringClass()

2 参数

3 返回值

一个表示底层成员声明类的对象。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Field getDeclaringClass()方法
 */
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;

public class GetDeclaringClass {

   public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
      Field field = SampleClass.class.getField("sampleField");
      Class declaringClass = field.getDeclaringClass();
      System.out.println(declaringClass.getName());
   }
}

@CustomAnnotation(name="SampleClass",  value = "Sample Class Annotation")
class SampleClass {

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   public String sampleField;

   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   }
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
   public String name();
   public String value();
}

输出结果为:

SampleClass

 

热门文章

优秀文章