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
A class parameter is simply an arbitrary name-value pair; you can use it to store any information you like about a class. To define a class-specific constant value. To provide parameterized values for method generator methods to use.
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
The following factory method creates Box instances dynamically based on user input: class BoxFactory { public: static Box *newBox(const std::string &description) { if (description == "pretty big box") return new PrettyBigBox; if (description == "small box") return new SmallBox; return 0; } };
Yes, you can do that. As stated in C# 4.0 specification, the grammar is extended to support dynamic wherever a type is expected: type: ...
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) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With