[英]Java method parameter for only annotated class
I hope I have chosen a title as clear as possible.我希望我选择了一个尽可能清晰的标题。 I have classes annotated with a custom annotation
我有用自定义注释注释的类
@MyAnnotation
public class MyClass1 {
//...
}
@MyAnnotation
public class MyClass2 {
//...
}
I have another class that I want to enrich with two methods with the same name: one method that takes only the annotated class as parameters, and the other method that takes other classes as parameters我有另一个类,我想用两个同名的方法来充实它:一个方法只将带注释的类作为参数,另一个方法将其他类作为参数
public class MyOtherClass {
public void myMethod(Object obj) {
//.....
}
public void myMethod (@MyAnnotation Object obj) {
// this method is applied for only classes annotated with @MyAnnotation
}
}
I know that public void myMethod (@MyAnnotation Object obj)
is a wrong way we can not pass annotation as parameter.我知道
public void myMethod (@MyAnnotation Object obj)
是一种错误的方式,我们不能将注释作为参数传递。 But I want to find the proper way to handle this need.但我想找到处理这种需求的正确方法。
You can have a single myMethod(Object obj)
and inside it manually check if the obj
passed to this method was annotated with @MyAnnotation
(supposing that the retention policy is to keep it at runtime).您可以有一个
myMethod(Object obj)
并在其中手动检查传递给此方法的obj
是否使用@MyAnnotation
进行注释(假设保留策略是在运行时保留它)。 Then dispatch calls to some private void processAnnotated(Object obj)
and private void processNotAnnotated(Object obj)
based on the result.然后根据结果将调用分派到一些
private void processAnnotated(Object obj)
和private void processNotAnnotated(Object obj)
。
public void myMethod(Object obj) {
if (obj != null && obj.getClass().isAnnotationPresent(MyAnnotation.class)) {
processAnnottated(obj);
} else {
processNotAnnottated(obj);
}
}
I am not sure what you are trying to achieve.我不确定你想要达到什么目的。 As you say, you can't annotate a parameter.
正如你所说,你不能注释一个参数。 You can mark an annotation as Runtime, but then you can only check with reflection if an annotation is present or not.
您可以将注释标记为运行时,但是如果注释存在与否,您只能使用反射检查。 So you could start myMethod with a call to a private validation method
validateMyAnnotationIsSet(parameter)
that checks if the annotation is set on the given class or not.因此,您可以通过调用私有验证方法
validateMyAnnotationIsSet(parameter)
来启动 myMethod,该方法检查是否在给定的类上设置了注释。
Perhaps it's better however to work with a MarkerInterface.然而,使用 MarkerInterface 可能更好。 You can create an empty interface that the class may or may not implement.
您可以创建一个空接口,该类可能会或可能不会实现该接口。 Within your method you can accept that interface as parameter and then do an 'instanceof' and a cast to continue to work with it.
在您的方法中,您可以接受该接口作为参数,然后执行“instanceof”和强制转换以继续使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.