开发者

Any way to force classes to have public static final field in Java?

Is there a way to force classes in Jav开发者_如何学JAVAa to have public static final field (through interface or abstract class)? Or at least just a public field?

I need to make sure somehow that a group of classes have

public static final String TYPE = "...";

in them.


No, you can't.

You can only force them to have a non-static getter method, which would return the appropriate value for each subclass:

public abstract String getType();

If you need to map each subclass of something to a value, without the need to instantiate it, you can create a public static Map<Class<?>, String> types; somewhere, populate it statically with all the classes and their types, and obtain the type by calling TypesHolder.types.get(SomeClass.class)


You can define an interface like this:

interface X {
   public static final String TYPE = "...";
}

and you can make classes implement that interface which will then have that field with the same value declared in the interface. Note that this practice is called the Constant interface anti-pattern.

If you want classes to have different values then you can define a function in the interface like this:

interface X {
   public String getType();
}

and implementing classes will have to implement the function which can return different values as needed.

Note: This works similarly with abstract classes as well.


There is no way to have the compiler enforce this but I would look into creating a custom FindBugs or CheckStyle rule which could check for this.


I don't think it's possible. But you could make an interface with a getType method


Or at least just a public field?

That's IMO the usual way to go: In the superclass, require a value in the constructor:

public abstract class MyAbstract {

  private final String type;

  protected MyAbstract(String type) {
    this.type = type;
  }

  public String getType() {
    return type;
  }
}

This way, all implementations must call that super-constructor - and they don't have to implement getType() each.


Implement an interface in your classes and call a method from that interface, like others have suggested.

If you must absolutely have a static field, you could make an unit-test that will go through the classes and checks with Reflection API that every class has that public static final field. Fail the build if that is not the case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜