Java 是否可以将类表示为字段?

Java 是否可以将类表示为字段?,java,reflection,annotations,Java,Reflection,Annotations,我需要在类中检索注释。 想象一下: @MyAnnotation(MyClass.class) public Table myTable; 我需要做的是从注释中的类初始化类表中的变量。 问题是,如何将表类表示为字段,以便从如下注释中检索值: Field tableField = ? // Here I should somehow cast 'this' to type Field Class annotationValue = tableField.getAnnotation(MyAnnota

我需要在类中检索注释。 想象一下:

@MyAnnotation(MyClass.class)
public Table myTable;
我需要做的是从注释中的类初始化类表中的变量。 问题是,如何将表类表示为字段,以便从如下注释中检索值:

Field tableField = ? // Here I should somehow cast 'this' to type Field
Class annotationValue = tableField.getAnnotation(MyAnnotation.class).value();

是否可以以某种方式将表类强制转换为字段类?

如果您只想作为
字段
对象访问
myTable
字段,您可以编写:

Field tableField = Enclosing.class.getDeclaredField("myTable");

其中
enclosuring
是声明
myTable
字段的类的名称。

如果您只是想作为
字段
对象访问
myTable
字段,您可以写:

Field tableField = Enclosing.class.getDeclaredField("myTable");
其中
enclosuring
是声明
myTable
字段的类的名称

字段表字段=?//在这里,我应该以某种方式将“this”转换为type字段

注释不依赖于类实例的
“this”
,而是依赖于类本身的属性。

问题是,如何按顺序将表类表示为字段 要从注释中检索值,请执行以下操作:

Field tableField = ? // Here I should somehow cast 'this' to type Field
Class annotationValue = tableField.getAnnotation(MyAnnotation.class).value();
通过思考

假设您有一个类:

public class MyObject{
  @MyAnnotation(MyClass.class)
  public Table myTable;
}
您可以通过以下方式检索字段:

Field tableField = MyObject.class.getDeclaredField("myTable"); 
然后使用该字段检索与注释关联的值:

Class<?> annotationValue = tableField.getAnnotation(MyAnnotation.class).value();
Class annotationValue=tableField.getAnnotation(MyAnnotation.Class).value();
字段表字段=?//在这里,我应该以某种方式将“this”转换为type字段

注释不依赖于类实例的
“this”
,而是依赖于类本身的属性。

问题是,如何按顺序将表类表示为字段 要从注释中检索值,请执行以下操作:

Field tableField = ? // Here I should somehow cast 'this' to type Field
Class annotationValue = tableField.getAnnotation(MyAnnotation.class).value();
通过思考

假设您有一个类:

public class MyObject{
  @MyAnnotation(MyClass.class)
  public Table myTable;
}
您可以通过以下方式检索字段:

Field tableField = MyObject.class.getDeclaredField("myTable"); 
然后使用该字段检索与注释关联的值:

Class<?> annotationValue = tableField.getAnnotation(MyAnnotation.class).value();
Class annotationValue=tableField.getAnnotation(MyAnnotation.Class).value();

注释用于元数据。这显然不是元数据。不要对此使用批注。批注用于元数据。这显然不是元数据。不要使用注释。好的,谢谢!但问题是,它不应该依赖于变量名或类,在我的例子中,该字段是在其中声明的。在这种情况下,我认为您应该尝试在编辑问题时重新制定您的要求。不太清楚,好的,谢谢!但问题是,它不应该依赖于变量名或类,在我的例子中,该字段是在其中声明的。在这种情况下,我认为您应该尝试在编辑问题时重新制定您的要求。这不是很清楚。