java反射举例---通过反射获取类、方法、属性、类中类

本文通过一个小例子来简单记录下如何使用java反射:

例子作用:获取Android有线网络下的网络信息,适用于Android5.0以上(机顶盒上有有线连接):

先上代码吧:

public void getEthernet(Context context){
        try{
            //根据反射获取到隐藏类
            Class ethernetManager = Class.forName("android.net.EthernetManager");
            //获取此类下的getConfiguration方法,无参
            Method method = ethernetManager.getMethod("getConfiguration");
            //获取EthernetManager类的一个实体对象
            Object obj = (context.getSystemService("ethernet"));
            //调用上面的method方法,返回的是一个对象ethernetDevInfo
            Object ethernetDevInfo = method.invoke(obj);
            //获取到ethernetDevInfo对象的class,因为后面还要调用这个类里面的方法
            Class devClass = ethernetDevInfo.getClass();
            //获取到devClass这个类中的getIpAssignment方法,注:这里获取方法只能通过class,不能通过对象
            Method method2 = devClass.getMethod("getIpAssignment");
            //调用method2这个方法,其中ethernetDevInfo是上面获取到的类对象,,ipAssignment就是我们要的结果
            Enum ipAssignment = (Enum) method2.invoke(ethernetDevInfo);
            LogUtils.d(TAG, "ipAssignment:" + ipAssignment);
            //获取到devClass这个类中的getStaticIpConfiguration方法
            Method getStaticIpConfiguration = devClass.getMethod("getStaticIpConfiguration");
            LogUtils.d(TAG, "5555555555:" + 111);
            //调用getStaticIpConfiguration这个方法,其中ethernetDevInfo是上面获取到的类对象,方法返回值又是一个对象
            Object staticIpConfiguration = getStaticIpConfiguration.invoke(ethernetDevInfo);
            //获取到staticIpConfiguration对象的class,因为后面还要调用这个类里面的属性
            Class staticIpConfigurationClass = staticIpConfiguration.getClass();
            //获取到staticIpConfigurationClass的属性值:ipAddress
            Field address = staticIpConfigurationClass.getDeclaredField("ipAddress");
            //获取到staticIpConfiguration这个对象中的ipAddress这个属性的值
            LinkAddress addressValue = (LinkAddress) address.get(staticIpConfiguration);
          
        }catch(NoSuchMethodError e){
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }catch(NoSuchMethodException e){
            e.printStackTrace();
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(InvocationTargetException e){
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace()
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值