有什么方法可以强制类在Java中具有public static final字段? [英] Any way to force classes to have public static final field in Java?
问题描述
是否有一种方法可以强制Java中的类具有公共静态最终字段(通过接口或抽象类)?还是至少是公共场所?
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?
我需要确保一组类具有
公共静态最终字符串TYPE ="...";
在其中.
推荐答案
不,你不能.
您只能强制它们使用非静态的getter方法,该方法将为每个子类返回适当的值:
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();
如果您需要将某物的每个子类映射到一个值,而无需实例化它,则可以创建一个 public static Map< Class<?> ;, String>.类型;
在某处,用所有类及其类型静态填充它,并通过调用 TypesHolder.types.get(SomeClass.class)
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)
这篇关于有什么方法可以强制类在Java中具有public static final字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!