mik*_*ike 6 java reflection constructor
我有一些类存储密钥和重要信息.没有其他人被允许创建密钥,因为密钥依赖于静态信息(如某些目录结构等).
public final class KeyConstants
{
private KeyConstants()
{
// could throw an exception to prevent instantiation
}
public static final Key<MyClass> MY_CLASS_DATA = new Key<MyClass>("someId", MyClass.class);
public static class Key<T>
{
public final String ID;
public final Class<T> CLAZZ;
private Key(String id, Class<T> clazz)
{
this.ID = id;
this.CLAZZ = clazz;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个例子很简单.
我想测试错误键(异常处理等)的后果,并通过JUnit测试用例中的反射实例化该类.
Constructor<?> c = KeyConstants.Key.class.getDeclaredConstructor(String.class, Class.class);
c.setAccessible(true);
@SuppressWarnings ("unchecked")
KeyConstants.Key<MyClass> r = (KeyConstants.Key<MyClass>) c.newInstance("wrongId", MyClass.class);
Run Code Online (Sandbox Code Playgroud)
然后我问自己如何防止进一步实例化密钥类(即防止通过反射进一步创建对象)?
enums 我想到了,但他们不使用泛型.
public enum Key<T>
{
//... Syntax error, enum declaration cannot have type parameters
}
Run Code Online (Sandbox Code Playgroud)
那么如何保留n泛型类的一组实例并阻止进一步的实例化呢?
如果我理解正确,您不希望实例化您的类。您可以将默认构造函数设置为私有
private Key() throws IllegalStateException //handle default constructor
{
throw new IllegalStateException();
}
Run Code Online (Sandbox Code Playgroud)
这将防止其不正确的实例化。
更新:添加抛出 IllegalStateException