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

时光总嘲笑我的痴心妄想 提交于 2021-01-21 07:48:06

问题


Is there a way to force classes in Java 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.


回答1:


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)




回答2:


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.




回答3:


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.




回答4:


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




回答5:


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.




回答6:


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.



来源:https://stackoverflow.com/questions/2464104/any-way-to-force-classes-to-have-public-static-final-field-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!