我有一个类如下:
public class MyClass {
private String key;
// Getter And Setter
}
我想限制key
值(例如它不能有空格字符),为此我必须定义为setter,如下所示:
public void setKey(String key)
{
if(key.indexOf(" ") != -1)
throw new RuntimeException("");
this.key = key;
}
我也在另一个类中使用了这个setter,是否可以定义一个注释,当调用setter方法时,它会检查这个?
如果是,如何?
最佳答案
这是不可能的。 您必须使用 @Retention(RetentionPolicy.RUNTIME) 编写自己的注释,并编写某种可以通过反射不断检查参数的工具。 对于参数来说这是不可能的,也不希望在类的每个实例中不断检查该方法的每次调用。
您可以实现某种类似于Objects
的实用程序类,而不是尝试使用注释来解决此问题:
public final class Strings {
/**
* Utility classes should not be instantiated.
*/
private Strings() {}
public static void requireWhiteSpace(String value) {
if (value == null || value.indexOf(" ") != -1) {
throw new IllegalArgumentException("Value should contain a white space character!")
}
}
}
然后像这样使用它:
public void setKey(String key) {
Strings.requireWhiteSpace(key);
this.key = key;
}
关于java - 如何用注解抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53369148/