这是我的代码。 它抛出
can not access a member of class sun.management.ClassLoadingImpl with modifiers "public"
我先反射(reflect)方法,再调用。如您所见,getObjectName 是一个公共(public)方法,但为什么我不能调用它?
我认为原始代码很困惑,我在这里粘贴一个明确的代码:
public class App {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Object bean = ManagementFactory.getClassLoadingMXBean();
Method[] methods = bean.getClass().getMethods();
for (Method method : methods) {
if (method.getName().equals("getObjectName")) {
System.out.println(method.getName() + ":" + method.invoke(bean).toString());
}
}
}
}
下面是旧...
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Hello world!
*/
public class App {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
Method[] methods = ManagementFactory.class.getMethods();
System.out.println(ManagementFactory.getClassLoadingMXBean().getObjectName());
for (Method method : methods) {
if (method.getName().startsWith("get") && method.getName().endsWith("Bean")) {
System.out.println(method.getName());
Object bean = method.invoke(null);
printBean(bean);
}
}
}
private static void printBean(Object bean) throws InvocationTargetException, IllegalAccessException {
Method[] methods = bean.getClass().getMethods();
for (Method method : methods) {
if (method.getName().startsWith("get")) {
System.out.println(method.getName());
System.out.println(method.getName() + ":" + method.invoke(bean).toString());
}
}
}
}
最佳答案
您不能传递 bean 实例来调用该方法,因为该类不是public
。您应该首先检查类的可见性:
if (!Modifier.isPublic(bean.getClass().getModifiers())) {
System.out.println(bean + " is not public");
return;
}
另一种可能性是将方法设置为可访问:
method.setAccessible(true);
关于java - 无法调用方法,即使它是公共(public)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44305205/