Please see these example classes.
A.java:
// A is not public
class A
{
public static void foo()
{
}
}
B.java:
package p;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class B
{
public void invoke() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException
{
Class clazz = Class.forName("A");
Method method = clazz.getDeclaredMethod("foo", new Class[0]);
method.invoke(null, new Object[0]);
}
}
C.java:
import java.lang.reflect.InvocationTargetException;
public class C extends p.B
{
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException
{
C c = new C();
c.invoke();
}
// @Override
// public void invoke() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException
// {
// Class clazz = Class.forName("A");
// Method method = clazz.getDeclaredMethod("foo", new Class[0]);
// method.invoke(null, new Object[0]);
// }
}
The 'invoke' method in main in C fails with:
IllegalAccessException: Class p.B can not access a member of class A with modifiers "public static"
If the 'invoke' method in C is exactly the same as the overriden method in p.B. However, if it is uncommented no Exception is being thrown.
Why the difference?
Aucun commentaire:
Enregistrer un commentaire