我有一个通用接口:
public interface Validator<T, M extends Serializable> {
...
}
以及几个实现该接口的类:
public class DocumentValidator implements Validator<DocumentDto, Serializable> {
...
}
public class ContractValidator implements Validator<ContractDto, Serializable> {
...
}
public class AccountValidator implements Validator<AccountDto, Serializable> {
...
}
如何以编程方式找出参数 T
? 例如,这里我试图通过传递 T
班级。
class SomeClass {
@Autowired
List<Validator> validators;
public Validator getValidatorForObject(Object object) {
validators.stream()
.filter(v -> ???)
.findFirst()
.orElseThrow(() -> new
GenericRuntimeException(ERROR_TYPE_VALIDATOR_NOT_FOUND.getText(object.getClass()));
}
}
1条答案
按热度按时间juud5qan1#
你可以找到
T
通过java反射输入,首先,得到getGenericInterfaces
那就去吧getActualTypeArguments
```validators.stream().filter((v) -> {
for (Type t : v.getClass().getGenericInterfaces()) {
ParameterizedType parameterizedType = (ParameterizedType) t;
Type type = parameterizedType.getActualTypeArguments()[0];
System.out.println(type);
}
// continue your code
// should return boolean value
}).findFirst().orElseThrow(() -> new GenericRuntimeException(ERROR_TYPE_VALIDATOR_NOT_FOUND.getText(object.getClass())));
class com.example.DocumentDto
class com.example.ContractDto