java保护构造函数是什么意思
我想知道为什么受保护的构造函数类可以在任何地方实例化。 我知道受保护字段只能在子类中使用 如jackson中的java保护构造函数是什么意思,java,Java,我想知道为什么受保护的构造函数类可以在任何地方实例化。 我知道受保护字段只能在子类中使用 如jackson中的org.codehaus.jackson.type.TypeReference,构造函数是受保护的,但它可以在任何代码中实例化 public abstract class TypeReference<T> implements Comparable<TypeReference<T>> { final Type _type; p
org.codehaus.jackson.type.TypeReference
,构造函数是受保护的,但它可以在任何代码中实例化
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;
}
}
可以从类或子类调用受保护的构造函数。如果您想“从内部”构造新对象,即从静态方法或从文件加载对象,这非常有用。可以从类或子类调用受保护的构造函数。如果您希望“从内部”构造新对象,即从静态方法或从文件加载对象,则此选项非常有用。您无法创建
类型引用,因为无论构造函数上的修饰符是什么,它都是抽象类
最有可能的使用方式是通过一个匿名类,它是这个类的一个子类,例如
TypeReference<List<String>> type = new TypeReference<List<String>>() { };
assert type.getClass() != TypeReference.class; // types are NOT the same.
TypeReference type=newtypereference(){};
断言类型。getClass()!=TypeReference.class;//类型不同。
您无法创建类型引用
,因为它是一个抽象类
,无论构造函数上的修饰符是什么
最有可能的使用方式是通过一个匿名类,它是这个类的一个子类,例如
TypeReference<List<String>> type = new TypeReference<List<String>>() { };
assert type.getClass() != TypeReference.class; // types are NOT the same.
TypeReference type=newtypereference(){};
断言类型。getClass()!=TypeReference.class;//类型不同。
ObjectMapper om=new ObjectMapper();readValue(jsonStr,newtypereference(){});ObjectMapper om=新的ObjectMapper();readValue(jsonStr,newtypereference(){});