Java for Web学习笔记(三三):自定义tag(1)篇外:Method和Function

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

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);
    }

}

相关链接: 我的Professional Java for Web Applications相关文章

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值