Reputation: 1724
I have a class as follow:
public class MyClass {
private String key;
// Getter And Setter
}
I want to limit key
value(for example it can't have space char), for this I have to define as setter as follow:
public void setKey(String key)
{
if(key.indexOf(" ") != -1)
throw new RuntimeException("");
this.key = key;
}
I used this setter in another class too, Is it possible to define an annotation that when setter method callded, it checked this?
If yes, How?
Upvotes: 0
Views: 2801
Reputation: 898
It is not possible.
You would have to write your own Annotation with @Retention(RetentionPolicy.RUNTIME)
and write some kind of tool which would constantly check the parameter via Reflection.
That's not possible for parameters and neither is it desirable to constantly check every call of that method in every instance of your class.
Instead of trying to solve this with an annotation you could implement some kind of utility class similar to 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!")
}
}
}
and then use it like this:
public void setKey(String key) {
Strings.requireWhiteSpace(key);
this.key = key;
}
Upvotes: 2