java - java protected 构造函数是什么意思

标签 java

我想知道为什么 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/

相关文章:

java - 如何为所有 Java Swing 窗口设置默认图标?

java - 如何使用 gradle 将 Artifactory 从 Artifactory 拉到项目类路径?

java - 使用正则表达式测试 Servlet 中的字符串

java - "[Fatal Error] :1:120: The processing instruction target matching "[xX][mM][lL] "is not allowed."

java - 如何有效地找到具有相同字符数的最长子串

java - 使用EMR/Spark将JSON转换为Parquet

Java:在 sin(x) 中计算 x

java - JTextField setDocument 覆盖文本

java - Hibernate:线程 "main"org.hibernate.MappingException 中出现异常:无效配置

java - 在 servlet 中启动一个新线程