How to dynamically determine a class that can be used as a parameter in a method?

I have a method that I use to check POJOs in Spring MVC (this allows me to rely on @Annotation in POJOs and at the same time check POJOs programmatically whenever and wherever I want, without using the @Valid annotation).

You must pass the object class to the method to verify:

 public void validate(Class clazz, Object model, BindingResult result){ ... Set<ConstraintViolation<clazz>> constraintViolations=validator.validate((clazz)model); for (ConstraintViolation<clazz> constraintViolation : constraintViolations) { ... } 

My code is wrong, since a get error:

clazz cannot be allowed for type

How can I change my code to be able to pass this method to any class I want?

thanks

+5
source share
3 answers

You can generify use the method

 public <T> void setList(Class<T> clazz){ List<T> list = new ArrayList<>(); } 

and name it as follows

 setList(Person.class) 
+4
source

You should use a generic:

 public <T> void setList(){ List<T> list = new ArrayList<>(); } ... obj.<Man>setList(); obj.<Woman>setList(); obj.<Person>setList(); 

or

  public <T> void setList(Class<T> clazz){ List<T> list = new ArrayList<>(); } ... obj.setList(Woman.class); obj.setList(Man.class); obj.setList(Person.class); 

or

 public static class MyClass <T> { public <T> void setList() { List<T> list = new ArrayList<>(); } } ... new MyClass<Woman>().setList(); new MyClass<Man>().setList(); new MyClass<Person>().setList(); 

Update: Instead of code

 public void validate(Class clazz, Object model, BindingResult result){ ... Set<ConstraintViolation<clazz>> constraintViolations=validator.validate((clazz)model); for (ConstraintViolation<clazz> constraintViolation : constraintViolations) { ... } 

use code

 public void <T> validate(Class<T> clazz, Object<T> model, BindingResult result){ ... Set<ConstraintViolation<T>> constraintViolations=validator.validate(model); for (ConstraintViolation<T> constraintViolation : constraintViolations) { ... } 
+2
source

I think you do not need a type and it can use an unrelated pattern:

 public void validate(Class<?> clazz, Object model, BindingResult result){ ... Set<ConstraintViolation<?>> constraintViolations=validator.validate(model); for (ConstraintViolation<?> constraintViolation : constraintViolations) { ... } 

https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

+2
source

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


All Articles