有些时候我们继承某类时,父类中的私有方法对子类不可以,但又不想去改变父类。这时可以利用java.reflect.Method的setAccessible方法来改变该私有方法的访问标志。
父类中getTime()方法是私有的。
package reflect; import java.text.SimpleDateFormat; import java.util.Date; public class OriginalMethod { private String getTime(){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss"); String time = sdf.format(date); return time; } public String getBjTime(){ return "BJ time is : " + getTime(); } }
子类中想引用这个方法:
package reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Child extends OriginalMethod {
static Method getTime = null;
static {
try {
getTime = OriginalMethod.class.getDeclaredMethod("getTime");
getTime.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
String getTJTime(){
String Tianji = "";
try {
Tianji = (String) getTime.invoke(this);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return "tian ji time is : " + Tianji;
}
public static void main(String[] args) {
String ss = new Child().getTJTime();
System.out.println(ss);
}
}