这是我的代码:
@Column(columnName="firstname")
private String firstName;
@Column(columnName="lastname")
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
是否有可能在另一个类阅读我的注释@Column(COLUMNNAME =“XYZ123”)的价值?
是的,如果你的列注释具有运行时保持
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
....
}
你可以做这样的事情
for (Field f: MyClass.class.getFields()) {
Column column = f.getAnnotation(Column.class);
if (column != null)
System.out.println(column.columnName());
}
UPDATE:要获得私有字段使用
Myclass.class.getDeclaredFields()
当然是的。这里有一个简单的注释:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String testText();
}
和样品注解的方法:
class TestClass {
@TestAnnotation(testText="zyx")
public void doSomething() {}
}
并且在打印testText的值另一个类的样品的方法:
Method[] methods = TestClass.class.getMethods();
for (Method m : methods) {
if (m.isAnnotationPresent(TestAnnotation.class)) {
TestAnnotation ta = m.getAnnotation(TestAnnotation.class);
System.out.println(ta.testText());
}
}
没有多少场注解像你的不同。
Cheerz!
我从来没有做过,但它看起来像Reflection提供这一点。 Field
是AnnotatedElement
,所以它具有getAnnotation
。 This page具有一个例子(以下复制);很简单,如果你知道类的注释,如果注释政策保留在运行时的注释。当然,如果将保留策略不会保留在运行时的注释,你将无法在运行时查询。
(?)这是因为被删除的答案提供了一个有用的链接an annotations tutorial,你可能会发现有用的;我在这里复制的链接,使人们可以使用它。
从this page例如:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
class Meta {
@MyAnno(str = "Two Parameters", val = 19)
public static void myMeth(String str, int i) {
Meta ob = new Meta();
try {
Class c = ob.getClass();
Method m = c.getMethod("myMeth", String.class, int.class);
MyAnno anno = m.getAnnotation(MyAnno.class);
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth("test", 10);
}
}
阐述到@Cephalopod的答案,如果你想在一个列表中,您可以使用此oneliner所有列名:
List<String> columns =
Arrays.asList(MyClass.class.getFields())
.stream()
.filter(f -> f.getAnnotation(Column.class)!=null)
.map(f -> f.getAnnotation(Column.class).columnName())
.collect(Collectors.toList());
虽然到目前为止给出的所有答案都完全有效的,一个也应该牢记的google reflections library一个更通用的,简单的方法来诠释扫描,如
Reflections reflections = new Reflections("my.project.prefix");
Set<Field> ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);
您还可以使用泛型类型,在我的情况下,考虑到一切说之前,你可以这样做:
public class SomeTypeManager<T> {
public SomeTypeManager(T someGeneric) {
//That's how you can achieve all previously said, with generic types.
Annotation[] an = someGeneric.getClass().getAnnotations();
}
}
请记住,这将不是100%equival到SomeClass.class.get(...)();
但可以做的伎俩...
在通常情况下,你对私人领域的访问,所以你不能在反射使用getFields。取而代之的是,你应该使用getDeclaredFields
所以,首先,你应该知道,如果你的列注释具有运行时保留:
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
}
之后,你可以这样做:
for (Field f: MyClass.class.getDeclaredFields()) {
Column column = f.getAnnotation(Column.class);
// ...
}
很显然,你愿意做一些与现场 - 使用注释值设置新的价值:
Column annotation = f.getAnnotation(Column.class);
if (annotation != null) {
new PropertyDescriptor(f.getName(), Column.class).getWriteMethod().invoke(
object,
myCoolProcessing(
annotation.value()
)
);
}
因此,完整的代码可以是这样的:
for (Field f : MyClass.class.getDeclaredFields()) {
Column annotation = f.getAnnotation(Column.class);
if (annotation != null)
new PropertyDescriptor(f.getName(), Column.class).getWriteMethod().invoke(
object,
myCoolProcessing(
annotation.value()
)
);
}
对于少数人要求一个通用的方法,这会帮助你(5年后:P)。
对于我下面的例子中,我拉着从具有RequestMapping注释方法RequestMapping URL值。为适应领域本,只是改变了
for (Method method: clazz.getMethods())
至
for (Field field: clazz.getFields())
和RequestMapping的交换使用的任何注释你正在寻找阅读。但要确保该注释具有@Retention(RetentionPolicy.RUNTIME)。
public static String getRequestMappingUrl(final Class<?> clazz, final String methodName)
{
// Only continue if the method name is not empty.
if ((methodName != null) && (methodName.trim().length() > 0))
{
RequestMapping tmpRequestMapping;
String[] tmpValues;
// Loop over all methods in the class.
for (Method method: clazz.getMethods())
{
// If the current method name matches the expected method name, then keep going.
if (methodName.equalsIgnoreCase(method.getName()))
{
// Try to extract the RequestMapping annotation from the current method.
tmpRequestMapping = method.getAnnotation(RequestMapping.class);
// Only continue if the current method has the RequestMapping annotation.
if (tmpRequestMapping != null)
{
// Extract the values from the RequestMapping annotation.
tmpValues = tmpRequestMapping.value();
// Only continue if there are values.
if ((tmpValues != null) && (tmpValues.length > 0))
{
// Return the 1st value.
return tmpValues[0];
}
}
}
}
}
// Since no value was returned, log it and return an empty string.
logger.error("Failed to find RequestMapping annotation value for method: " + methodName);
return "";
}