Person.class.getInterfaces() 注意使用方法

Person.class.getInterfaces() 注意使用方法

  • 如果此对象表示一个接口,则该数组包含表示该接口扩展的所有接口的对象。数组中接口对象顺序与此对象所表示的接口的声明的 extends 子句中接口名顺序一致。

  • 如果此对象表示一个不实现任何接口的类或接口,则此方法返回一个长度为 0 的数组。

  • 如果此对象表示一个基本类型或 void,则此方法返回一个长度为 0 的数组。

代码演示

package main.tcp.dubbo.test;

interface Person{
}
class Son implements Person{
}

public class TestDemo {
    public static void main(String[] args) {
        // 如果此对象表示一个不实现任何接口的类或接口,则此方法返回一个长度为 0 的数组。
        System.out.println(Person.class.getInterfaces().length); // 输出结果是:0
        System.out.println(Son.class.getInterfaces()[0]); // 输出结果是:interface main.tcp.dubbo.test.Person

        ReflectInterface target = new ReflectInterfaceImpl();
        System.out.println(target.getClass().getInterfaces()[0]);// 输出结果是:interface main.tcp.dubbo.test.ReflectInterface
        System.out.println(new Class[]{ReflectInterface.class}[0]);// 输出结果是:interface main.tcp.dubbo.test.ReflectInterface
        System.out.println(ReflectInterface.class.getInterfaces().length); //  输出结果是:0
        System.out.println(target.getClass());// 输出结果是:class main.tcp.dubbo.test.ReflectInterfaceImpl
        System.out.println(ReflectInterface.class); // 输出结果是: interface main.tcp.dubbo.test.ReflectInterface

        // 反射中第二个参数需要传入被代理类的接口数组,那么就有这几种写法了,如下:
        // ReflectInterfaceImpl.class.getInterfaces()
        // new Class<?>[]{ReflectInterface.class} // 推荐使用这种,灵活易用
        // target.getClass().getInterfaces()
        ReflectInterface  service = (ReflectInterface)Proxy
                .newProxyInstance(ReflectInterface.class.getClassLoader()
                        ,new Class[]{ReflectInterface.class}
                        ,(obj, method, params) -> {
                    System.out.println("param="+ Arrays.asList(params));
                    String response = (String)method.invoke(target, params);
                    return response;
                });
        System.out.println(service.hello("我是入参"));
    }
}

class ReflectInterfaceImpl implements ReflectInterface{
    @Override
    public String hello(String param) {
        System.out.println("=================param="+param);
        return "放屁";
    }
}

运行结果:

0
interface main.tcp.dubbo.test.Person
interface main.tcp.dubbo.test.ReflectInterface
interface main.tcp.dubbo.test.ReflectInterface
0
class main.tcp.dubbo.test.ReflectInterfaceImpl
interface main.tcp.dubbo.test.ReflectInterface
param=[我是入参]
=================param=我是入参
放屁

Process finished with exit code 0

总结一句话,该类是否有父类接口,有的话就会有返回,否则数组长度为0,相当于没有元素返回。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔道不误砍柴功

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值