Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict method to accept only object as parameter instead of Class Objects as Type Literals?

Tags:

java

generics

I wanted to pass object as a parameter instead of class object as type literal. I tried many ways but did not get output.

public <T> List<Map<String,Object>> getUIElementsList(Class<T> requiredType) {
       doSomeThing();
       return this.fieldList;
}

If i'm running above code that will accept following values as parameter passing. If I have a FormBean class then

FormBean formBean = new FormBean();  
formBean.setUserId(252528); 
getUIElementsList(FormBean.class); //restrict this case
getUIElementsList(formBean); 

I want that method can only accept already created intance object. I can not even use newInstance() method to create another object because i required old object instance values also.

Any suggestions?

like image 348
michaeln peterson Avatar asked Oct 30 '22 14:10

michaeln peterson


1 Answers

The Class<T> itself represents some instance, too - this is an instance of the type Class, parameterized by the type T.

I think the best you can do is to add a check if the provided type is instance of Class and if yes, throw an IllegalArgumentException:

public <T> List<Map<String,Object>> getUIElementsList(T value) {
    if (value instanceof Class) { 
        throw new IllegalArgumentException("Class instances are not supported");
    }
    ..
}

When defining type-parameters, you're only allowed to bound them by intersections of existing (families of) types, but not to apply negation on given types, like the thing you aim for, which is something like "all types but one".

like image 172
Konstantin Yovkov Avatar answered Nov 15 '22 05:11

Konstantin Yovkov