[英]Is it possible to represent a Class as a Field?
I need to retrieve annotation inside a class. 我需要在一个类中检索注释。 Imagine this:
想象一下:
@MyAnnotation(MyClass.class)
public Table myTable;
What I need to do is to initialize a variable inside class Table from a class inside the annotation. 我需要做的是从注解中的类初始化类Table中的变量。 The question is, how can I represent Table class as a field in order to retrieve a value from annotation like this:
问题是,如何将Table类表示为字段,以便从这样的注释中检索值:
Field tableField = ? // Here I should somehow cast 'this' to type Field
Class annotationValue = tableField.getAnnotation(MyAnnotation.class).value();
Is it possible to cast a Table class into a Field class somehow? 是否可以通过某种方式将Table类转换为Field类?
If you simply want access to the myTable
field as a Field
object, you would write: 如果只想将
myTable
字段作为Field
对象访问,则应编写:
Field tableField = Enclosing.class.getDeclaredField("myTable");
where Enclosing
is the name of the class in which the myTable
field is declared. 其中,
Enclosing
是其中的类的名称myTable
字段声明。
Field tableField = ?
字段tableField =? // Here I should somehow cast 'this' to type Field
//在这里我应该以某种方式将'this'转换为Field
An annotation doesn't depend on "this"
, that is an instance of the class, but depends on the the class itself. 批注不依赖于
"this"
(即类的实例),而是依赖于类本身。
The question is, how can I represent Table class as a field in order to retrieve a value from annotation like this:
问题是,如何将Table类表示为字段,以便从这样的注释中检索值:
By reflection. 通过反思。
Suppose you have the class : 假设您有上课:
public class MyObject{
@MyAnnotation(MyClass.class)
public Table myTable;
}
You could retrieve the field in this way : 您可以通过以下方式检索字段:
Field tableField = MyObject.class.getDeclaredField("myTable");
And then use the field to retrieve the value associated to the annotation: 然后使用该字段检索与注释关联的值:
Class<?> annotationValue = tableField.getAnnotation(MyAnnotation.class).value();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.