Reputation: 119
I want to know why a protected constructor class can be instantiated anywhere. I know protected field only can be used in subclass.
Such as org.codehaus.jackson.type.TypeReference
in Jackson, constructor is protected, but it can be instantiated in any code.
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;
}
}
Upvotes: 0
Views: 541
Reputation: 533492
You can't create a TypeReference
because it is an abstract class
no matter what the modifier on the constructor is.
Most likely the way you are using this is via an anonymous class which is a sub-class of this class e.g.
TypeReference<List<String>> type = new TypeReference<List<String>>() { };
assert type.getClass() != TypeReference.class; // types are NOT the same.
Upvotes: 0
Reputation: 35795
A protected constructor can be called from the class or from subclasses. This is useful if you want to construct new objects "from within", i.e. from a static method or by loading them from a file.
Upvotes: 4