Sam*_*Sam 4 java generics compiler-errors
我有一个用于实例化对象的通用方法如下:
@Override
public <T> T createRawObject(Class<?> raw_type,
ProviderParam param)
{
SpringProviderParam spring_param = (SpringProviderParam) param;
ApplicationContext ctx = SpringContextGenericProvider.getInstance()
.generate(param,
ApplicationContext.class,
(Object[]) spring_param.getContextPaths());
ValidateUtility.notNull(ctx, "Target Application_Context is null");
T raw_object= (T) ctx.getBean((spring_param.getBeanName()!=null)?spring_param.getBeanName():raw_type);
ValidateUtility.sameType(raw_object, raw_type, "Target object isn't instance of a {} class", raw_type);
return raw_object;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是以下行:
T raw_object= (T) ctx.getBean((spring_param.getBeanName()!=null)?spring_param.getBeanName():raw_type);
Run Code Online (Sandbox Code Playgroud)
此行未编译并显示以下编译错误:
The method getBean(String) in the type BeanFactory is not applicable for the arguments (Serializable)
Run Code Online (Sandbox Code Playgroud)
但是当我将这一行更改为以下行并编译好时:
T raw_object= null;
if(spring_param.getBeanName()!=null)
raw_object= (T) ctx.getBean(spring_param.getBeanName());
else
raw_object= (T) ctx.getBean(raw_type);
Run Code Online (Sandbox Code Playgroud)
我对这个问题含糊不清.
这里的问题是编译器无法检测到你试图在第一个片段中调用哪个方法,因为你的三元运算符返回不同类型的对象,因此你得到编译错误,因为你可以使用不同的方法从上下文中获取bean(按名称) - 字符串,按类 - 类).
假设您正在尝试设置的值
(spring_param.getBeanName()!=null)?spring_param.getBeanName():raw_type
Run Code Online (Sandbox Code Playgroud)
对于任何变量,您必须告诉编译器哪个类型将是您的变量.你可以在这里使用任何类型的变量类型,但Object class因为它们没有任何其他共同的祖先(我的意思是String和Class类).