Java - Alternatives to forcing subclass to have a static method

前端 未结 5 1461

I often find I want to do something like this:

class Foo{
public static abstract String getParam();
}

To force a subclasses of Foo to retur

5条回答
  •  轮回少年
    2021-01-07 23:04

    The best you can do here in a static context is something like one of the following:

    a. Have a method you specifically look for, but is not part of any contract (and therefore you can't enforce anyone to implement) and look for that at runtime:

     public static String getParam() { ... };
     try {
         Method m = clazz.getDeclaredMethod("getParam");
         String param = (String) m.invoke(null);
     }
     catch (NoSuchMethodException e) {
       // handle this error
     }
    

    b. Use an annotation, which suffers from the same issue in that you can't force people to put it on their classes.

    @Target({TYPE})
    @Retention(RUNTIME)
    public @interface Param {
       String value() default "";
    }
    
    @Param("foo")
    public class MyClass { ... }
    
    
    public static String getParam(Class clazz) {
       if (clazz.isAnnotationPresent(Param.class)) {
          return clazz.getAnnotation(Param.class).value();
       }
       else {
          // what to do if there is no annotation
       }
    }
    

提交回复
热议问题