简体   繁体   中英

field.setInt() with annotations - java

EDITED:

OK, so say I have annotations @X and @Y

public class MyExampleClass{
  @X @Y Integer myfield;
}

The problem I am having is that when I call

field.setInt(o, new Integer(65)));

I get an error

java.lang.IllegalArgumentException: Can not set java.lang.Integer field MyExampleClass.myfield to (int)65

This is how field is initialized:

Field field = o.getClass().getField(fieldname);

o is an Object parameter. When I call it, I pass it an object of type MyExampleClass , and the value of fieldname is "myfield" .

Here is the stack trace:

java.lang.IllegalArgumentException: Can not set java.lang.Integer field MyExampleClass.myfield to (int)65
java.lang.IllegalArgumentException: Can not set java.lang.Integer field MyExampleClass.myfield to (int)65
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(
UnsafeFieldAccessorImpl.java:167)
        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(
UnsafeFieldAccessorImpl.java:191)
        at sun.reflect.UnsafeObjectFieldAccessorImpl.setInt(UnsafeObjectFieldAcc
essorImpl.java:114)
        at java.lang.reflect.Field.setInt(Field.java:943)
        at MyCallingClass.get(MyCallingClass.java:111)
        at MyTester.main(MyTester.java:20)

An object does not have annotations. A field, class, method, etc. (see the @Target annotation) can be annotated, but the concept of annotated object does not exist. Annotations are just meta data. And they are constants.

What you are asking for is not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM