简体   繁体   中英

How to dynamically define the Class that can be used as a parameter in a method?

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

In need to pass the Class of the object to the method in order to validate:

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 not correct, since a get the error:

clazz cannot be resolved to a type

How should I edit my code in order to be able to pass to this method any Class I want?

Thank you

You can generify the method

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

and call it as follows

setList(Person.class)

You should use 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) {
...
}

I guess you don't need a type and can use an unbound wildcard:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM