(原创)android 反射机制Demo
来源:互联网 发布:php支付宝接口开发步骤 编辑:程序博客网 时间:2024/05/21 14:51
废话不多说,直接看项目,注释已够详细了。
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); }}
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; }}
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); }}
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); }}
项目链接:
0 0
- (原创)android 反射机制Demo
- 反射机制小Demo
- java反射机制demo
- Java反射机制demo
- 【反射】PHP的反射机制【原创】
- java反射机制的Demo
- 反射机制的实现demo
- Java 反射机制学习Demo
- 反射机制构建web应用(Demo)
- 反射机制构建web应用(Demo)
- java反射机制超简单Demo
- C++ 反射机制的实现Demo
- Java笔记-反射机制(三)-小demo
- Android反射机制
- Android反射机制
- Android反射机制
- Android反射机制详解
- Android反射机制
- Android中的Binder机制的简要理解
- 实现add方法,add(2,3)、add(2)(3)都返回5
- Arduino学习(三)点亮LED灯
- 【Java开发环境IDEA】类头设置注释User信息
- android中根据控件宽度,实现展示文本内容,解决中英文自动换行
- (原创)android 反射机制Demo
- 重载
- 初始Python
- Android中使用加速度传感器
- 206. Reverse Linked List
- Java 内存区域和GC机制最详解
- Linux 文件搜索命令 find
- Git操作手册|命令速查表
- 软件测试 (一) 软件测试方法