Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8210

restrict class type of annotation

is there any ClassDef like IntDef in annotation to restrict the type of annotation as my example below?

@ClassDef({
    Integer, String, Long
})
public @interface MyRestrictedData {
}

As a result, I can use it as: public void showData(@MyRestrictedData Object myData)

Upvotes: 0

Views: 961

Answers (1)

Dean Xu
Dean Xu

Reputation: 4711

This reqirement CAN'T be resolve by annotation processor.

It can only do by runtime container, like Spring.

But in fact, the container is just help you check it by proxy. Why can't you do it by yourself? Like this:

public class MyRestrictedData {
  public static void check(Object o){
    if(!(String.class.isInstance(o) || Integer.class.isInstance(o) || Long.class.isInstance(o)))
      throw new IllegalArgumentException("Must be String, Integer or Long.");
  }
}

public void showData(Object myData) {
  MyRestrictedData.check(myData);
  // then do your work
}

EDIT

If you really want check in compile period, the only way is what zhh said, override your method. I don't know what logic need handle String, Integer and Long together. But if you really need, you can do:

public void showData(String s){
  showData((Object)s);
}

public void showData(Integer i){
  showData((Object)i);
}

public void showData(Long l){
  showData((Object)l).
}

private void showData(Object o){
  // do your work here, note this method is PRIVATE
}

Upvotes: 1

Related Questions