简体   繁体   English

为什么无法访问公共静态方法?

[英]Why a public static method is not accessible?

I'm trying to reflect the parse(CharSequence, DateTimeFormatter) methods from classes which each extends the TemporalAccessor class.我试图从每个扩展TemporalAccessor类的类中反映parse(CharSequence, DateTimeFormatter)方法。

    private static final Map<Class<?>, MethodHandle> PARSE_HANDLES = synchronizedMap(new HashMap<>());

    static <T extends TemporalAccessor> MethodHandle parseMethodHandle(final Class<T> clazz) {
        if (clazz == null) {
            throw new NullPointerException("clazz is null");
        }
        return PARSE_HANDLES.computeIfAbsent(clazz, k -> {
            try {
                final Method method = clazz.getMethod("parse", CharSequence.class, DateTimeFormatter.class);
                log.debug("method: {}, {}", method, method.isAccessible());
                // i don't understand; public static method is not accessible? yet it isn't.
                assert method.isAccessible(); // NOT GOOD with UTs
                return MethodHandles.lookup().unreflect(method);
            } catch (final ReflectiveOperationException roe) {
                throw new RuntimeException(roe);
            }
        });
    }

With the YearMonth class, I got this.通过YearMonth课程,我得到了这个。

method: public static java.time.YearMonth java.time.YearMonth.parse(java.lang.CharSequence,java.time.format.DateTimeFormatter), false

Why a public static method is not accessible?为什么无法访问public static方法?

See the documentation for isAccessible :请参阅isAccessible的文档

This method is deprecated because its name hints that it checks if the reflected object is accessible when it actually indicates if the checks for Java language access control are suppressed.此方法已被弃用,因为它的名称暗示它检查反射对象是否可访问,而实际上它指示是否禁止检查 Java 语言访问控制。 This method may return false on a reflected object that is accessible to the caller.此方法可能会在调用者可访问的反射对象上返回false To test if this reflected object is accessible, it should use canAccess(Object) .要测试此反射对象是否可访问,应使用canAccess(Object)

(My emphasis.) (我的重点。)

With the Java Reflection API, you can override the accessibility of methods by setting the accessible flag.使用 Java 反射 API,您可以通过设置可访问标志来覆盖方法的可访问性 This can be performed by method.setAccessible(true) .这可以通过method.setAccessible(true)来执行。

Now the isAccessible() method does not what you think it does, but it simply checks, if the standard java access checks are currently overridden.现在isAccessible()方法不是您认为的那样,它只是检查标准 java 访问检查当前是否被覆盖。

This means, that you can of course invoke the method with reflection if the standard access modifiers allow it.这意味着,如果标准访问修饰符允许,您当然可以通过反射调用该方法。 Otherwise, you had to set the accessible flag.否则,您必须设置可访问标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM