How to restrict a method to accept only an object as a parameter instead of class objects as standard literals?

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

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

If I run over code that will take the following values โ€‹โ€‹as a parameter pass. If I have a FormBean class, then

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

I want this method to only accept an already created intance object. I can't even use the newInstance () method to create another object, because I also need the values โ€‹โ€‹of the instances of the old object.

Any suggestions?

+5
source share
1 answer

Class<T> also represents some instance - it is an instance of type Class , parameterized by type T

I think the best you can do is add a check if the provided type is an instance of Class , and if so, 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 are allowed to associate them only with intersections of existing (families) of types, but do not apply negation to given types, for example, to the goal you are aiming for, something like "all types" but one. "

+2
source

Source: https://habr.com/ru/post/1237322/


All Articles