java反射详解 (二)

【案例】通过反射操作属性

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 


【案例】通过反射取得并修改数组的信息:

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

【案例】通过反射修改数组大小

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中有三种类类加载器。

1Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。

2Extension ClassLoader 用来进行扩展类的加载,一般对应的是jre\lib\ext目录中的类

3AppClassLoader 加载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); 
  } 
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值