Java: static abstract (again) - best practice how to work around

后端 未结 9 1105
误落风尘
误落风尘 2021-02-01 16:30

I theoretically understand the point why there is no abstract static in Java, as explained for instance in Why can't static methods be abstract in

9条回答
  •  孤街浪徒
    2021-02-01 17:13

    To restate the problem: you want your per-file-type classes to have statically available information on the type (e.g., name and description).

    We can easily get part-way there: create a separate class for your type info, and have a static instance of this (appropriately instantiated) in each per-file-type class.

    package myFileAPI;
    
    public class TypeInfo { 
        public final String name;
        public final String description;
    
        public TypeInfo(String name, String description) {
            this.name = name;
            this.description = description;
        }
    }
    

    and, say:

    package myFileAPI;
    
    public class TextFile {
        public static final TypeInfo typeInfo
                       = new TypeInfo("Text", "Contains text.");
    }
    

    Then you can do stuff like:

    System.out.println(TextFile.typeInfo.name);
    

    (Of course, you could also use getters in TypeInfo to encapsulate the underlying strings.)

    However, as you said, what we really want is to enforce the existence of a particular signature static method in all your per-file-type classes at compile time, but the 'obvious' design path leads to requiring an abstract static method in a common superclass which isn't allowed.

    We can enforce this at run-time though, which may be good enough to ensure it is coded correctly. We introduce a File superclass:

    package myFileAPI;
    
    public abstract class File {
    
        public static TypeInfo getTypeInfo() {
            throw new IllegalStateException(
                        "Type info hasn't been set up in the subclass");
        }
    
    }
    

    If TextFile now extends File, we will get this exception when calling TextFile.getTypeInfo() at runtime, unless TextFile has a same-signature method.

    This is quite subtle: code with TextFile.getTypeInfo() in still compiles, even when there is no such method in TextFile. Even though static methods are bound at compile time, the compiler can still look through the class hierarchy to determine the compile-time static call target.

    So, we need code like:

    package myFileAPI;
    
    public class TextFile extends File {
    
        private static final TypeInfo typeInfo
                          = new TypeInfo("Text", "Contains text.");
    
        // Shadow the superclass static method
        public static TypeInfo getTypeInfo() {
            return typeInfo;
        }
    
    }
    

    Note that we are still shadowing the superclass method, and so File.getTypeInfo() can still be 'meaninglessly' called.

提交回复
热议问题