gpt4 book ai didi

Java反射: how to call a method with private interface as argument?

转载 作者:行者123 更新时间:2023-11-30 05:41:45 26 4
gpt4 key购买 nike

在 Java 中,我通常通过反射调用一个方法,该方法使用接口(interface)作为参数,通过使用以下方法构建我的参数:

Method method = theClass.getMethod("methodName", new Class[]{ IAnyInterface.class });

但是当接口(interface)嵌套在私有(private)类中时,我不知道如何执行此操作:JSomething.INestedInterface,其中JSomething私有(private):

private class JSomething {
public void init(INestedInterface iSomething) {
...
}

public interface INestedInterface {
public void notify();
}

...
}

这里使用它甚至无法编译,因为接口(interface)不可访问:

Method method = theClass.getMethod("init", new Class[]{JSomething.INestedInterface.class});

我已经创建了一个准备调用的代理处理程序,但当我无法使用嵌套接口(interface)名称时,我无法尝试构建 class 参数,有什么建议吗?

最佳答案

嗯,您确定您的代码可以通过在类前添加 private 进行编译吗?
对于第一级类不允许使用可见性修饰符。根据JLS 8.1.1

The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration.

<小时/>

但无论如何,您也可以通过反射提取Class;)

final Class<?> clazz = Class.forName("your.package.JSomething$INestedInterface");
theClass.getMethod("methodName", new Class[]{ clazz });

或者,如果您的 JSomething 类本身就是一个内部 静态

final Class<?> clazz = Class.forName("your.package.WrapperClass$JSomething$INestedInterface");
theClass.getMethod("methodName", new Class[]{ clazz });

请注意,每个“嵌套级别”都由 $ 符号标记,并且您传入的 String 称为类的二进制名称(参见JLS 13.1)。

The binary name of a top level type (§7.6) is its canonical name (§6.7).

The binary name of a member type (§8.5, §9.5) consists of the binary name of its immediately enclosing type, followed by $, followed by the simple name of the member.

<小时/>

顺便说一句,getMethod 接受 var-arg 参数,因此您可以只提交单个值

theClass.getMethod("methodName", clazz);

关于Java反射: how to call a method with private interface as argument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55505250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com