(原创)android 反射机制Demo

废话不多说,直接看项目,注释已够详细了。

1. 效果图



2. 实现类

MainActivity
package com.example.lainanzhou.filetest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.channels.FileChannel;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void write(View view) {
        String fileName = getFilesDir().getAbsolutePath() + "/test1.txt";
        byte[] bytes = new byte[8 * 1024 * 1024];
        File file = new File(fileName);
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "rw");
            raf.write(bytes);// 写入占用8M空间的空白文件
            raf.close();
            Log.d("MainActivity", "File length: " + new File(fileName).length() / 1024 / 1024);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void read(View view) {
        String fileName = getFilesDir().getAbsolutePath() + "/test1.txt";
        Log.d("MainActivity", "File length: " + new File(fileName).length() / 1024 / 1024);
        //        byte[] bytes = new byte[1024 * 1024];
        String str = "aaa";
        File file = new File(fileName);
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(file, "rw");
            FileChannel fc = raf.getChannel();
            //将文件大小截为0:清空文件内容
            fc.truncate(0);
            raf.write(str.getBytes());// 重新写入数据
            raf.close();
            Log.d("MainActivity", "File length: " + new File(fileName).length());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 反射直接获取对应的包下的操作类进行set和get操作
     *
     * @param view
     */
    public void reflect(View view) {
        try {
            // 反射获取对应类
            Class<?> demo = Class.forName("com.example.lainanzhou.filetest.ReflectBean");
            // 使用该方式获取实例注意:构造函数必须有不带参的,不然会报: java.lang.InstantiationException
            //            ReflectBean reflectBean = (ReflectBean) demo.newInstance();
            //            reflectBean.setName("Joker");
            //            reflectBean.setAge(20);
            //            Log.d(TAG, " ReflectBean " + reflectBean.toString());

            // 另外种方式可以不需要设置不带参构造函数
            Constructor<?> cons[] = demo.getConstructors(); //取得全部的构造函数
            ReflectBean reflectBean = (ReflectBean) cons[0].newInstance("Joker", 20);
            // 两种方式同样可以设置参数
            Log.d(TAG, " ReflectBean " + reflectBean.toString());

            // 获取操作类实现类
            Class<?> intes[] = demo.getInterfaces();
            for (int i = 0; i < intes.length; i++) {
                Log.d(TAG, " ReflectBean 实现接口:" + intes[i].getName());
            }

            //取得父类
            Class<?> superclass = demo.getSuperclass();
            Log.d(TAG, " ReflectBean 继承的父类为:   " + superclass.getName());

            // 获取里面所有方法及返回类型
            Method method[] = demo.getMethods();
            for (int i = 0; i < method.length; ++i) {
                Class<?> returnType = method[i].getReturnType();
                //                Class<?> para[] = method[i].getParameterTypes();
                //                int temp = method[i].getModifiers();
                //                Log.d(TAG, " ReflectBean " + Modifier.toString(temp) + " ");
                Log.d(TAG, " ReflectBean returnType" + " : " + returnType.getName());
                Log.d(TAG, " ReflectBean method" + i + " : " + method[i].getName());
                //                System.out.print("(");
                //                for (int j = 0; j < para.length; ++j) {
                //                    System.out.print(para[j].getName() + " " + "arg" + j);
                //                    if (j < para.length - 1) {
                //                        System.out.print(",");
                //                    }
                //                }
            }

            // 调用操作类中的方法: 后面是参数类型
            Method testInterface = demo.getMethod("testInterface", String.class);
            testInterface.invoke(reflectBean, "Joker from testInterface");// 后面是需要传入的数据

            // 通过反射操作属性
            Field field = demo.getDeclaredField("age");// 获取私有的属性
            field.setAccessible(true);// 设置可操作属性
            field.set(reflectBean, 21);// 设置属性值
            Log.d(TAG, "操作属性" + field.get(reflectBean));

        } catch (Exception e) {
            Log.d(TAG, " Exception " + e.toString());
            e.printStackTrace();
        }
    }


    /**
     * 通过类加载器获取对应操作类里面接口实现其方法
     *
     * @param v
     */
    public void getClassLoader(View v) {
        MyInvocationHandler demo = new MyInvocationHandler();
        ReflectInterface sub = (ReflectInterface) demo.bind(new ReflectBean("Joker", 22));
        sub.testInterface("Joker from MyInvocationHandler");
    }

    /**
     * 类加载构造器,需要实现InvocationHandler接口
     */
    class MyInvocationHandler implements InvocationHandler {
        private Object obj = null;

        public Object bind(Object obj) {
            this.obj = obj;
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
                    .getClass().getInterfaces(), this);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            Object temp = method.invoke(this.obj, args);
            return temp;
        }
    }

    public void factory(View v) {
        try {
            Properties pro = FactoryManager.getPro(this);
            ReflectInterface reflectInterface = FactoryManager.getInstance(pro.getProperty("one"));
            if (reflectInterface != null) {
                reflectInterface.testInterface("Joker from FactoryManager");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ReflectInterface
package com.example.lainanzhou.filetest;

/**
 * @author Joker
 * @since 2016/9/21.
 */
interface ReflectInterface {
    void testInterface(String name);
}

ReflectBean 
package com.example.lainanzhou.filetest;

import android.util.Log;

/**
 * @author Joker
 * @since 2016/9/21.
 */
public class ReflectBean extends ReflectSuper implements ReflectInterface {
    private String name;
    private int age;

    //    public ReflectBean() {
    //    }

    public ReflectBean(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "ReflectBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public void testInterface(String name) {
        Log.d("MainActivity", "testInterface: " + name);
    }
}

ReflectSuper 
package com.example.lainanzhou.filetest;

/**
 * @author Joker
 * @since 2016/9/21.
 */
public class ReflectSuper {
}

FactoryManager 
package com.example.lainanzhou.filetest;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author Joker
 * @since 2016/9/22.
 */
public class FactoryManager {
    public static ReflectInterface getInstance(String ClassName) {
        ReflectInterface rfInterface = null;
        try {
            rfInterface = (ReflectInterface) Class.forName(ClassName).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rfInterface;
    }

    /**
     * 操作文件属性的方法
     *
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static Properties getPro(Context context) throws FileNotFoundException, IOException {
        Properties pro = new Properties();
        File f = new File(context.getFilesDir() + "/reflectInterface.properties");
        if (f.exists()) {
            pro.load(new FileInputStream(f));
        } else {
            pro.setProperty("one", "com.example.lainanzhou.filetest.ProduceOne");
            pro.setProperty("two", "com.example.lainanzhou.filetest.ProduceTwo");
            pro.store(new FileOutputStream(f), "REFLECTINTERFACE CLASS");
        }
        return pro;
    }
}

ProduceOne 
package com.example.lainanzhou.filetest;

import android.util.Log;

/**
 * @author Joker
 * @since 2016/9/22.
 */
public class ProduceOne implements ReflectInterface {
    @Override
    public void testInterface(String name) {
        Log.d("ProduceOne", "ProduceOne: " + name);
    }
}

ProduceTwo 
package com.example.lainanzhou.filetest;

import android.util.Log;

/**
 * @author Joker
 * @since 2016/9/22.
 */
public class ProduceTwo implements ReflectInterface {
    @Override
    public void testInterface(String name) {
        Log.d("ProduceTwo", "ProduceTwo: " + name);
    }
}


项目链接:


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值