我想知道为什么 protected 构造函数类可以在任何地方实例化。 我知道 protected 字段只能在子类中使用。
如Jackson中的org.codehaus.jackson.type.TypeReference
,构造函数是 protected ,但可以在任何代码中实例化。
public abstract class TypeReference<T>
implements Comparable<TypeReference<T>> {
final Type _type;
protected TypeReference()
{
Type superClass = getClass().getGenericSuperclass();
if (superClass instanceof Class<?>) { // sanity check, should never happen
throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information");
}
/* 22-Dec-2008, tatu: Not sure if this case is safe -- I suspect
* it is possible to make it fail?
* But let's deal with specifc
* case when we know an actual use case, and thereby suitable
* work arounds for valid case(s) and/or error to throw
* on invalid one(s).
*/
_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public Type getType() { return _type; }
/**
* The only reason we define this method (and require implementation
* of <code>Comparable</code>) is to prevent constructing a
* reference without type information.
*/
@Override
public int compareTo(TypeReference<T> o) {
// just need an implementation, not a good one... hence:
return 0;
}
}
最佳答案
protected 构造函数可以从类或子类中调用。如果您想“从内部”构造新对象,即从静态方法或从文件加载它们,这非常有用。
关于java - java protected 构造函数是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35869281/