2013-03-24 77 views
1

调用没有修饰符的类或默认类我想要调用默认访问类Demo的主要方法:是否可以通过反射

class Demo { 
    public static void main(String[] args) { 
     System.out.println("Hello World!"); 
    } 
} 

,我把它从另一个类,如:

String[] str = {}; 
    Class cls = Class.forName(packClassName);   
    Method thisMethod = cls.getMethod("main", String[].class);   
    thisMethod.setAccessible(true);   
    thisMethod.invoke(cls.newInstance(), (Object) str); 

但我得到的例外,即

java.lang.IllegalAccessException: Class javaedit.Editor can not access a member of class Demo with modifiers "" 
     at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95) 
     at java.lang.Class.newInstance0(Class.java:366) 
+3

莫非哟你告诉我们你如何试图调用它? – Pshemo 2013-03-24 11:03:46

+0

请不要张贴相关的代码作为表扬。而应该通过[[edit]]选项将其包含在提问中。 – Pshemo 2013-03-24 11:09:13

+0

您是否真的需要使用反射,还是仅仅因为您在堆栈轨迹中看到“反射”而询问反射?我会在同一个包中直接调用Demo.main方法编写公共类,而不使用反射。 – VGR 2013-03-24 11:22:24

回答

3

代码的主要问题是,你正在试图调用实例上的静态方法的类。静态方法不属于对象,但对整个班级,所以不是实例中使用null作为invoke方法的第一个参数

String[] str = {}; 
Class cls = Class.forName(packClassName);   
Method thisMethod = cls.getMethod("main", String[].class);   
thisMethod.setAccessible(true);   

thisMethod.invoke(null, new Object[]{str});//ver 1 
thisMethod.invoke(null, (Object)str);//ver 2 
+0

非常感谢你亲爱的... – 2013-03-24 12:09:05

2

如果你知道这可以用反射来实现类的全名,例如给出包专用类:

class AcessCheck { 

    public static final void printStuff() { 
     System.out.println("Stuff"); 
    } 
} 

您可以使用以下调用printStuff方法与反思:

final Class<?> c = Thread.currentThread().getContextClassLoader().loadClass("com.mypackage.AcessCheck"); 
    final Method m = c.getDeclaredMethod("printStuff", (Class[]) null); 
    m.setAccessible(true); 
    m.invoke(null, (Object[]) null);