Method
protected方法可以在同一个package或者继承的子类中使用,但是在某些偶然的情况下,会希望能够使用某个类的protected方法。
越权使用protected方法
下面是一个测试的类,定义了1个静态方法p1,和1个动态方法p2。
public class Test {
protected static void p1(String a, String b){
System.out.println("a = " + a + ", b = " + b);
}
protected void p2(String a, String b){
System.out.println("a = " + a + " ---p2 ---- b = " + b);
}
}
在另一个package中,我们通过Method类来调用这两个方法。
//调用静态的protected方法
try{
Method m1 = Test.class.getDeclaredMethod("p1", String.class,String.class);
m1.setAccessible(true); //这部是关键,允许访问
m1.invoke(null,"hello","world");
}catch(Exception e){
e.printStackTrace();
}
//调用动态的protected方法
try{
Method m2 = Test.class.getDeclaredMethod("p2", String.class,String.class);
m2.setAccessible(true);
Test myTest = new Test();
m2.invoke(myTest,"hello","world");
}catch(Exception e){
e.printStackTrace();
}
Method的其他用途
上面演示的是调用本不能使用的protected method,需要注意的是private的方法是不能被调用的,如果是public方法,就无需专门进行m.setAccessible(true);实际上我们可以利用Method将方法作为的参数进行传递。
Function
前面已经提及可以用Method作为方法的对象。在C语言中,可以将function作为参数进行传递。在Java1.8开始提供了Function类。我们看看例子:
public class Test {
//定义了一个静态的方法f1,类A实例作为参数。
private static String f1(A a){
return a.toString();
}
//定义了一个动态的方法f2,类B实例作为参数。
private String f2(B b){
return b.toString();
}
public static void sampleTest(A a,B b){
//静态Function调用
Function<A, String> func1 = Test::f1;
String result1 = func1.apply(a);
System.out.println("result1 = " + result1);
//动态的Function调用
Test test = new Test();
Function<B, String> func2 = test::f2;
String result2 = func2.apply(b);
System.out.println("result2 = " + result2);
}
}
上面演示了通过Function来调用方法的例子,下面给出如何将func作为参数进行传递的例子,我们在上面的例子上进行一点小修改:
public class Test {
private static String f1(A a){
return a.toString();
}
private String f2(B b){
return b.toString();
}
//增加一个方法,将Function作为第一个参数,Function中的参数作为第二个参数进行传递。
private <T> String f(Function<T, String> func, T value){
return func.apply(value);
}
public static void sampleTest(A a,B b){
Test test = new Test();
Function<A, String> func1 = Test::f1;
String result1 = test.f(func1,a);
System.out.println("result1 = " + result1);
Function<B, String> func2 = test::f2;
String result2 = test.f(func2,b);
System.out.println("result2 = " + result2);
}
}

本文介绍了如何在Java中利用反射机制调用受保护的方法,并展示了如何使用Java 8引入的Function接口来传递和调用方法。
324

被折叠的 条评论
为什么被折叠?



