在做项目中,有时候可能要对其他包中的其他类private 方法,这个时候我们就可以通过反射来调啦。
package com.service;
import java.lang.reflect.Method;
public class ReflectionDemo {
public static void main(String[] args) {
try {
Class<com.service.ReflectionDemo> clazz = com.service.ReflectionDemo.class;
//Class clazz = Class.forName("com.service.ReflectionDemo");
ReflectionDemo rd = clazz.newInstance();
Method method = clazz.getDeclaredMethod("init");
method.setAccessible(true);
method.invoke(rd);
method = clazz.getDeclaredMethod("init",new Class []{String.class});
method.setAccessible(true);
method.invoke(rd, new Object[]{"Mr.Wei"});
} catch (Exception e) {
e.printStackTrace();
}
}
public ReflectionDemo(){}
private void init(){
System.out.println("ReflectionDemo Bingo....");
}
private void init (String userName){
System.out.println(userName+" ReflectionDemo Bingo....");
}
}