Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I ambiguity with a generic method

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.

like image 770
Sam Avatar asked Jan 14 '23 00:01

Sam


1 Answers

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).

like image 152
Arsen Alexanyan Avatar answered Jan 17 '23 19:01

Arsen Alexanyan