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

1、通过反射获取隐藏类:

Class ethernetManager = Class.forName("android.net.EthernetManager");

2、通过反射获取EthernetManager类的getConfiguration方法:

Method method = ethernetManager.getMethod("getConfiguration");

注:因为这个方法是无参的,所以这样写即可,若是有参数的话需要在后面加上参数,比如有一个String参数:

Method method = ethernetManager.getMethod("getConfiguration",String.class);

3、获取EthernetManager的一个对象(后面调用方法的时候需要用):

Object obj = (context.getSystemService("ethernet"));

注:这里因为EthernetManager是唯一的,可以直接通过getSystemService方法获取它的对象,其他的类的话可以通过ethernetManager.newInstance()或者其他方式获取

4、方法调用:

Object ethernetDevInfo = method.invoke(obj);

注:这里的这个方法获取的是一个对象。

5、下面我们需要再次调用获取到的对象里面的某一个方法:

Class devClass = ethernetDevInfo.getClass();
Method method2 = devClass.getMethod("getIpAssignment");

注:在这里我们需要先获取ethernetDevInfo这个对象的class,通过这个class才能找到他的方法,否则会报错

6、调用上面获取的ethernetDevInfo对象的method2方法,获取到的是一个枚举值:

Enum ipAssignment = (Enum) method2.invoke(ethernetDevInfo);

7、获取对象中的属性值:

Method getStaticIpConfiguration = devClass.getMethod("getStaticIpConfiguration");
//调用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);

 

例子很简单,只是为了说明一下反射怎么使用。具体反射里面的方法,大家可以点进去自己看看:

比如获取所有方法:Class.getMethods()

获取所有属性:Class.getFields()等等。

 

下面贴一下上面代码中使用到的:EthernetManager.class 、IpConfiguration.class

public class EthernetManager {
    private static final String TAG = "EthernetManager";

    private final Context mContext;
    private final IEthernetManager mService;

    /**
     * Create a new EthernetManager instance.
     * Applications will almost always want to use
     * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
     * the standard {@link android.content.Context#ETHERNET_SERVICE Context.ETHERNET_SERVICE}.
     */
    public EthernetManager(Context context, IEthernetManager service) {
        mContext = context;
        mService = service;
    }

    /**
     * Get Ethernet configuration.
     * @return the Ethernet Configuration, contained in {@link IpConfiguration}.
     */
    public IpConfiguration getConfiguration() {
        if (mService == null) {
            return new IpConfiguration();
        }
        try {
            return mService.getConfiguration();
        } catch (RemoteException e) {
            return new IpConfiguration();
        }
    }

    /**
     * Set Ethernet configuration.
     */
    public void setConfiguration(IpConfiguration config) {
        if (mService == null) {
            return;
        }
        try {
            mService.setConfiguration(config);
        } catch (RemoteException e) {
        }
    }
}

 

package android.net;

import android.net.StaticIpConfiguration;
import android.os.Parcel;
import android.os.Parcelable;

import java.util.Objects;

/**
 * A class representing a configured network.
 * @hide
 */
public class IpConfiguration implements Parcelable {
    private static final String TAG = "IpConfiguration";

    public enum IpAssignment {
        /* Use statically configured IP settings. Configuration can be accessed
         * with staticIpConfiguration */
        STATIC,
        /* Use dynamically configured IP settigns */
        DHCP,
        /* no IP details are assigned, this is used to indicate
         * that any existing IP settings should be retained */
        UNASSIGNED
    }

    public IpAssignment ipAssignment;

    public StaticIpConfiguration staticIpConfiguration;

    public enum ProxySettings {
        /* No proxy is to be used. Any existing proxy settings
         * should be cleared. */
        NONE,
        /* Use statically configured proxy. Configuration can be accessed
         * with httpProxy. */
        STATIC,
        /* no proxy details are assigned, this is used to indicate
         * that any existing proxy settings should be retained */
        UNASSIGNED,
        /* Use a Pac based proxy.
         */
        PAC
    }

    public ProxySettings proxySettings;

    public ProxyInfo httpProxy;

    private void init(IpAssignment ipAssignment,
                      ProxySettings proxySettings,
                      StaticIpConfiguration staticIpConfiguration,
                      ProxyInfo httpProxy) {
        this.ipAssignment = ipAssignment;
        this.proxySettings = proxySettings;
        this.staticIpConfiguration = (staticIpConfiguration == null) ?
                null : new StaticIpConfiguration(staticIpConfiguration);
        this.httpProxy = (httpProxy == null) ?
                null : new ProxyInfo(httpProxy);
    }

    public IpConfiguration() {
        init(IpAssignment.UNASSIGNED, ProxySettings.UNASSIGNED, null, null);
    }

    public IpConfiguration(IpAssignment ipAssignment,
                           ProxySettings proxySettings,
                           StaticIpConfiguration staticIpConfiguration,
                           ProxyInfo httpProxy) {
        init(ipAssignment, proxySettings, staticIpConfiguration, httpProxy);
    }

    public IpConfiguration(IpConfiguration source) {
        this();
        if (source != null) {
            init(source.ipAssignment, source.proxySettings,
                 source.staticIpConfiguration, source.httpProxy);
        }
    }

    public IpAssignment getIpAssignment() {
        return ipAssignment;
    }

    public void setIpAssignment(IpAssignment ipAssignment) {
        this.ipAssignment = ipAssignment;
    }

    public StaticIpConfiguration getStaticIpConfiguration() {
        return staticIpConfiguration;
    }

    public void setStaticIpConfiguration(StaticIpConfiguration staticIpConfiguration) {
        this.staticIpConfiguration = staticIpConfiguration;
    }

    public ProxySettings getProxySettings() {
        return proxySettings;
    }

    public void setProxySettings(ProxySettings proxySettings) {
        this.proxySettings = proxySettings;
    }

    public ProxyInfo getHttpProxy() {
        return httpProxy;
    }

    public void setHttpProxy(ProxyInfo httpProxy) {
        this.httpProxy = httpProxy;
    }

    @Override
    public String toString() {
        StringBuilder sbuf = new StringBuilder();
        sbuf.append("IP assignment: " + ipAssignment.toString());
        sbuf.append("\n");
        if (staticIpConfiguration != null) {
            sbuf.append("Static configuration: " + staticIpConfiguration.toString());
            sbuf.append("\n");
        }
        sbuf.append("Proxy settings: " + proxySettings.toString());
        sbuf.append("\n");
        if (httpProxy != null) {
            sbuf.append("HTTP proxy: " + httpProxy.toString());
            sbuf.append("\n");
        }

        return sbuf.toString();
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }

        if (!(o instanceof IpConfiguration)) {
            return false;
        }

        IpConfiguration other = (IpConfiguration) o;
        return this.ipAssignment == other.ipAssignment &&
                this.proxySettings == other.proxySettings &&
                Objects.equals(this.staticIpConfiguration, other.staticIpConfiguration) &&
                Objects.equals(this.httpProxy, other.httpProxy);
    }

    @Override
    public int hashCode() {
        return 13 + (staticIpConfiguration != null ? staticIpConfiguration.hashCode() : 0) +
               17 * ipAssignment.ordinal() +
               47 * proxySettings.ordinal() +
               83 * httpProxy.hashCode();
    }

    /** Implement the Parcelable interface */
    public int describeContents() {
        return 0;
    }

    /** Implement the Parcelable interface  */
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(ipAssignment.name());
        dest.writeString(proxySettings.name());
        dest.writeParcelable(staticIpConfiguration, flags);
        dest.writeParcelable(httpProxy, flags);
    }

    /** Implement the Parcelable interface */
    public static final Creator CREATOR =
        new Creator() {
            public IpConfiguration createFromParcel(Parcel in) {
                IpConfiguration config = new IpConfiguration();
                config.ipAssignment = IpAssignment.valueOf(in.readString());
                config.proxySettings = ProxySettings.valueOf(in.readString());
                config.staticIpConfiguration = in.readParcelable(null);
                config.httpProxy = in.readParcelable(null);
                return config;
            }

            public IpConfiguration[] newArray(int size) {
                return new IpConfiguration[size];
            }
        };
}

还有这个StaticIpConfiguration .class简单列一下得了:

public class StaticIpConfiguration implements Parcelable {
    public LinkAddress ipAddress;
    public InetAddress gateway;
    public final ArrayList dnsServers;
    public String domains;
......
}

 

你可能感兴趣的:(java)