I have a generic method for instantiating a object as following:
@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;
}
My problem is with following line:
T raw_object= (T) ctx.getBean((spring_param.getBeanName()!=null)?spring_param.getBeanName():raw_type);
this line didn't compiled and show following compile-error:
The method getBean(String) in the type BeanFactory is not applicable for the arguments (Serializable)
but when I change this line to following lines and compiled fine:
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);
I ambiguity with this problem.
The problem here is that compiler cannot detect which method you are trying to call in the first snippet because your ternary operator returning different types of objects, therefore you are getting compilation error, because you can get the beans from context using different methods (by name - String, by class - Class).
Suppose that you are trying to set the value of the
(spring_param.getBeanName()!=null)?spring_param.getBeanName():raw_type
to any variable, you have to tell the compiler which type will be your variable. You can use nothing here for your variable type but Object class
, because they haven't any other common ancestor (I mean String
and Class
classes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With