Reputation: 49
I'm reading the source code about spring, and want to know the class of return value that is generic, What should I do?
public static <T> T getBean(String name) {
assertContextInjected();
System.out.println();
return (T) applicationContext.getBean(name);
}
Upvotes: 0
Views: 45
Reputation: 5034
Unfortunately, in Java the short answer is that you can't. You can consider Generics as basically just a compile-time feature to ensure correct handling. However, the compiled bytecode discards all the type information in a process called "Type Erasure", so effectively what the JVM gets at runtime is simply :
public static Object getBean(String name) {
However, none of that is the root cause of your problem, which is to do with your call. I assume you have something like :
SomeClass someVariable = getBean("someName");
What's happening is that the bean that you have requested is not of type SomeClass (and casting is not going to help you with that) - So what you need to do is figure out what class the bean is that Spring is giving you, and then change the "SomeClass" in the caller to expect that type.
Upvotes: 2