1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class AccessPrivateMember {
public static void main(String[] args) { try { Class c = Class.forName("com.example.reflect.HelloService"); Method publicMethod = c.getMethod("publicHello", String.class);
Method saySomething = c.getMethod("publicHello", String.class); Method thisClassMethod = c.getDeclaredMethod("privateHello", String.class); thisClassMethod.setAccessible(true); publicMethod.invoke(c.newInstance(), "publicMethod"); saySomething.invoke(c.newInstance(), "saySomething");
thisClassMethod.invoke(c.newInstance(), "thisClassMethod");
}catch (Exception e) { e.printStackTrace(); } } }
|