I have a Class<? extends Annotation>
and tried calling newInstance()
but Java yelled at me for the obvious reason that I can't instantiate an interface. But I know frameworks like EasyMock are perfectly capable of instantiating interfaces. What would it take to get a completely dumb Annotation
instance out of my Class
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Thanks to Affe for pointing me the right direction - I'd comment on his answer but then I wouldn't be able to format the solution:
works like a charm.If you know the type of the annotation at compile time, you can just create a class that implements the annotation as if it was a normal annotation. See also this answer.
Mock frameworks do not instantiate interfaces, they build classes that implement them on the fly at runtime. You may find this javadoc enlightening for what you want to do!
You can't create an instance of a class that's not fully specified.
To illustrate, calling
newInstance()
on a class of typeClass<Object>
would definately create an Object, but callingnewInstance()
on a class of typeClass<?>
would leave the compiler wondering which class out of the entire universe of possibilities it should construct.Just because you have narrowed the field down a bit by specifying that instead of just
?
, you want a?
that extendsAnnotation
doesn't mean you've actually named a particular class to construct.? extends Annotation
just means "some class that extendsAnnotation
" Without naming the exact class, the ClassLoader cannot figure out which constructor to call, because there is no limit to the number of classes that might extendAnnotation
.EasyMock doesn't instantiate Interfaces. I'm not familiar with the framework, but it likely instantiates java.lang.Object(s) which extend the desired interface, or it instantiates some sort of "behind the scenes" framework class which was generated with an "implements interface" clause in the class definition. Interfaces don't have a default constructor.