Alternatives to static methods on interfaces for enforcing consistency

前端 未结 7 2368
孤城傲影
孤城傲影 2020-12-05 02:43

In Java, I\'d like to be able to define marker interfaces, that forced implementations to provide static methods. For example, for simple text-serialization/deserialization

7条回答
  •  忘掉有多难
    2020-12-05 03:21

    As @aperkins said, you should use enums.

    The enum base class, Enum, provides a valueOf method that will convert a string to an instance.

    enum MyEnum { A, B, C; }
    // Here's your toText
    String strVal = MyEnum.A.getName();
    // and here's your fromText
    MyEnum value = MyEnum.valueOf(MyEnum.class, strVal);
    

    Update: For the ones that are enums, this might do what you need. It uses reflection, so you only need to implement EnumHelper on enums where you have to deal with legacy values.

    /** Enums can implement this to provide a method for resolving a string
      * to a proper enum name.
      */
    public interface EnumHelp
    {
        // Resolve s to a proper enum name that can be processed by Enum.valueOf
        String resolve(String s);
    }
    
    /** EnumParser provides methods for resolving symbolic names to enum instances.
      * If the enum in question implements EnumHelp, then the resolve method is
      * called to resolve the token to a proper enum name before calling valueOf.
      */
    public class EnumParser
    {
        public static > T fromText(Class cl, String s) {
            if (EnumHelp.class.isAssignableFrom(cl)) {
                try {
                    Method resolve = cl.getMethod("resolve", String.class);
                    s = (String) resolve.invoke(null, s);
                }
                catch (NoSuchMethodException ex) {}
                catch (SecurityException ex) {}
                catch(IllegalAccessException ex) {}
                catch(IllegalArgumentException ex) {}
                catch(InvocationTargetException ex) {}
            }
            return T.valueOf(cl, s);
        }
    
        public > String toText(T value)
        {
            return value.name();
        }
    }
    

提交回复
热议问题