【案例】经过反射操做属性html
- class hello {
- public static void main(String[] args) throws Exception {
- Class<?> demo = null;
- Object obj = null;
- demo = Class.forName("Reflect.Person");
- obj = demo.newInstance();
- Field field = demo.getDeclaredField("sex");
- field.setAccessible(true);
- field.set(obj, "男");
- System.out.println(field.get(obj));
- }
- }// end class
【案例】经过反射取得并修改数组的信息:java
- import java.lang.reflect.*;
- class hello{
- public static void main(String[] args) {
- int[] temp={1,2,3,4,5};
- Class<?>demo=temp.getClass().getComponentType();
- System.out.println("数组类型: "+demo.getName());
- System.out.println("数组长度 "+Array.getLength(temp));
- System.out.println("数组的第一个元素: "+Array.get(temp, 0));
- Array.set(temp, 0, 100);
- System.out.println("修改以后数组第一个元素为: "+Array.get(temp, 0));
- }
- }
【运行结果】:
数组类型: int
数组长度 5
数组的第一个元素: 1
修改以后数组第一个元素为: 100工具
【案例】经过反射修改数组大小ui
- class hello{
- public static void main(String[] args) {
- int[] temp={1,2,3,4,5,6,7,8,9};
- int[] newTemp=(int[])arrayInc(temp,15);
- print(newTemp);
- System.out.println("=====================");
- String[] atr={"a","b","c"};
- String[] str1=(String[])arrayInc(atr,8);
- print(str1);
- }
- /**
- * 修改数组大小
- * */
- public static Object arrayInc(Object obj,int len){
- Class<?>arr=obj.getClass().getComponentType();
- Object newArr=Array.newInstance(arr, len);
- int co=Array.getLength(obj);
- System.arraycopy(obj, 0, newArr, 0, co);
- return newArr;
- }
- /**
- * 打印
- * */
- public static void print(Object obj){
- Class<?>c=obj.getClass();
- if(!c.isArray()){
- return;
- }
- System.out.println("数组长度为: "+Array.getLength(obj));
- for (int i = 0; i < Array.getLength(obj); i++) {
- System.out.print(Array.get(obj, i)+" ");
- }
- }
- }
【运行结果】:
数组长度为: 15
1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 =====================
数组长度为: 8
a b c null null null null null
动态代理
【案例】首先来看看如何得到类加载器:
- class test{
- }
- class hello{
- public static void main(String[] args) {
- test t=new test();
- System.out.println("类加载器 "+t.getClass().getClassLoader().getClass().getName());
- }
- }
【程序输出】:
类加载器 sun.misc.Launcher$AppClassLoader
其实在java中有三种类类加载器。
1)Bootstrap ClassLoader 此加载器采用c++编写,通常开发中不多见。
2)Extension ClassLoader 用来进行扩展类的加载,通常对应的是jre\lib\ext目录中的类
3)AppClassLoader 加载classpath指定的类,是最经常使用的加载器。同时也是java中默认的加载器。
若是想要完成动态代理,首先须要定义一个InvocationHandler接口的子类,已完成代理的具体操做。
- package Reflect;
- import java.lang.reflect.*;
- //定义项目接口
- interface Subject {
- public String say(String name, int age);
- }
- // 定义真实项目
- class RealSubject implements Subject {
- @Override
- public String say(String name, int age) {
- return name + " " + age;
- }
- }
- 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;
- }
- }
- class hello {
- public static void main(String[] args) {
- MyInvocationHandler demo = new MyInvocationHandler();
- Subject sub = (Subject) demo.bind(new RealSubject());
- String info = sub.say("Rollen", 20);
- System.out.println(info);
- }
- }
【运行结果】:
Rollen 20
类的生命周期
在一个类编译完成以后,下一步就须要开始使用类,若是要使用一个类,确定离不开JVM。在程序执行中JVM经过装载,连接,初始化这3个步骤完成。
类的装载是经过类加载器完成的,加载器将.class文件的二进制文件装入JVM的方法区,而且在堆区建立描述这个类的java.lang.Class对象。用来封装数据。 可是同一个类只会被类装载器装载之前
连接就是把二进制数据组装为能够运行的状态。
连接分为校验,准备,解析这3个阶段
校验通常用来确认此二进制文件是否适合当前的JVM(版本),
准备就是为静态成员分配内存空间,。并设置默认值
解析指的是转换常量池中的代码做为直接引用的过程,直到全部的符号引用均可以被运行程序使用(创建完整的对应关系)
完成以后,类型也就完成了初始化,初始化以后类的对象就能够正常使用了,直到一个对象再也不使用以后,将被垃圾回收。释放空间。
当没有任何引用指向Class对象时就会被卸载,结束类的生命周期
将反射用于工厂模式
先来看看,若是不用反射的时候,的工厂模式吧:
http://www.cnblogs.com/rollenholt/archive/2011/08/18/2144851.html
- interface fruit{
- public abstract void eat();
- }
- class Apple implements fruit{
- public void eat(){
- System.out.println("Apple");
- }
- }
- class Orange implements fruit{
- public void eat(){
- System.out.println("Orange");
- }
- }
- // 构造工厂类
- // 也就是说之后若是咱们在添加其余的实例的时候只须要修改工厂类就好了
- class Factory{
- public static fruit getInstance(String fruitName){
- fruit f=null;
- if("Apple".equals(fruitName)){
- f=new Apple();
- }
- if("Orange".equals(fruitName)){
- f=new Orange();
- }
- return f;
- }
- }
- class hello{
- public static void main(String[] a){
- fruit f=Factory.getInstance("Orange");
- f.eat();
- }
- }
这样,当咱们在添加一个子类的时候,就须要修改工厂类了。若是咱们添加太多的子类的时候,改的就会不少。
如今咱们看看利用反射机制:
- package Reflect;
- interface fruit{
- public abstract void eat();
- }
- class Apple implements fruit{
- public void eat(){
- System.out.println("Apple");
- }
- }
- class Orange implements fruit{
- public void eat(){
- System.out.println("Orange");
- }
- }
- class Factory{
- public static fruit getInstance(String ClassName){
- fruit f=null;
- try{
- f=(fruit)Class.forName(ClassName).newInstance();
- }catch (Exception e) {
- e.printStackTrace();
- }
- return f;
- }
- }
- class hello{
- public static void main(String[] a){
- fruit f=Factory.getInstance("Reflect.Apple");
- if(f!=null){
- f.eat();
- }
- }
- }
如今就算咱们添加任意多个子类的时候,工厂类就不须要修改。
上面的爱吗虽然能够经过反射取得接口的实例,可是须要传入完整的包和类名。并且用户也没法知道一个接口有多少个可使用的子类,因此咱们经过属性文件的形式配置所须要的子类。
下面咱们来看看: 结合属性文件的工厂模式
首先建立一个fruit.properties的资源文件,
内容为:
- apple=Reflect.Apple
- orange=Reflect.Orange
而后编写主类代码:
- package Reflect;
- import java.io.*;
- import java.util.*;
- interface fruit{
- public abstract void eat();
- }
- class Apple implements fruit{
- public void eat(){
- System.out.println("Apple");
- }
- }
- class Orange implements fruit{
- public void eat(){
- System.out.println("Orange");
- }
- }
- //操做属性文件类
- class init{
- public static Properties getPro() throws FileNotFoundException, IOException{
- Properties pro=new Properties();
- File f=new File("fruit.properties");
- if(f.exists()){
- pro.load(new FileInputStream(f));
- }else{
- pro.setProperty("apple", "Reflect.Apple");
- pro.setProperty("orange", "Reflect.Orange");
- pro.store(new FileOutputStream(f), "FRUIT CLASS");
- }
- return pro;
- }
- }
- class Factory{
- public static fruit getInstance(String ClassName){
- fruit f=null;
- try{
- f=(fruit)Class.forName(ClassName).newInstance();
- }catch (Exception e) {
- e.printStackTrace();
- }
- return f;
- }
- }
- class hello{
- public static void main(String[] a) throws FileNotFoundException, IOException{
- Properties pro=init.getPro();
- fruit f=Factory.getInstance(pro.getProperty("apple"));
- if(f!=null){
- f.eat();
- }
- }
- }
下面这个是一个比较完整的反射工具类,用来得到一个类里面属性的具体信息
- package util;
- import java.lang.reflect.*;
- /**
- * 获取Class的信息
- *
- */
- public class ClassInfo {
- //须要反射的JAVA类型
- private static Class reflectionClass;
- private static String[][] relation;
- private static String[] constructors;
- private static String[] methods;
- private static String[] fields;
- //加载须要反射的类
- public static void load(String reflectionClassName) {
- try {
- reflectionClass = null;
- reflectionClass = Class.forName(reflectionClassName);
- } catch (ClassNotFoundException e) {
- System.err.println(e.getMessage());
- }
- }
- //获取类关系
- public static String[][] getRelation() {
- String superClassName = reflectionClass.getSuperclass().getSimpleName();
- Class[] interfaceClass = reflectionClass.getInterfaces();
- if(superClassName == null)
- superClassName = "Have not super class!";
- if (reflectionClass.getInterfaces().length == 0) {
- relation = new String[2][1];
- relation[1][0] = "Have not interface!";
- }else {
- relation = new String[2][reflectionClass.getInterfaces().length];
- for (int i = 0; i < interfaceClass.length; i++) {
- relation[1][i] = interfaceClass[i].getName();
- System.out.println( "interfaceClass:"+relation[1][i] );
- }
- }
- relation[0][0] = superClassName;
- System.out.println( "superClassName:"+superClassName );
- return relation;
- }
- //获取构造方法
- public static String[] getConstructors() {
- Constructor[] constructor = reflectionClass.getDeclaredConstructors();
- constructors = new String[constructor.length];
- for (int i = 0; i < constructor.length; i++) {
- Class[] paramType = constructor[i].getParameterTypes();
- String param = "";
- for (int j = 0; j < paramType.length; j++) {
- param += paramType[j].getSimpleName().toString() + " ";
- }
- constructors[i] = constructor[i].getName().toString()
- + "(" + param + ")";
- System.out.println("constructor:"+ constructors[i] );
- }
- return constructors;
- }
- //获取类方法
- public static String[] getMethods() {
- Method[] method = reflectionClass.getDeclaredMethods();
- methods = new String[method.length];
- for (int i = 0; i < method.length; i++) {
- Class[] paramType = method[i].getParameterTypes();
- String param = "";
- for (int j = 0; j < paramType.length; j++) {
- param += paramType[j].getSimpleName().toString() + " ";
- }
- methods[i] = method[i].getName().toString()
- + "(" + param + ")";
- System.out.println("method:"+ methods[i]);
- }
- return methods;
- }
- //获取类属性
- public static String[] getFields() {
- Field[] field = reflectionClass.getDeclaredFields();
- fields = new String[field.length];
- for (int i = 0; i < field.length; i++) {
- field[i].setAccessible( true ); //容许访问私有属性
- fields[i] = field[i].toGenericString();
- String type=field[i].getGenericType().toString();
- System.out.println("fields:"+fields[i]+" type:"+type);
- }
- return fields;
- }
- //私有方法,被外部调用
- private void testInvoke() {
- System.out.println("invoke!");
- }
- private void testInvoke(String str) {
- System.out.println("invoke!:" + str);
- }
- }