码迷,mamicode.com
首页 > 编程语言 > 详细

读书笔记_java设计模式深入研究 第二章 反射

时间:2014-12-02 00:12:42      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:des   style   io   ar   color   os   使用   sp   java   

1,JDK中反射类包含的内容:
    -1,Class类,代表一个类。
    -2,Constructor,代表类的构造方法。
    -3,Field,代表类成员
    -4,Method,代表方法。
2,统一调用形式:
    一个基本的使用反射的例子如下:
package com.use;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class A {
    int m;//m
    
    /**
     * empty constructor
     */
    public A(){
        
    }
    /**
     * 带参数的构造方法
     * @param m
     */
    public A(int m){
        
        this.= m;
    }
    /**
     * 
     */
    public void func(){
        
        System.out.println("Hello Java!");
    }
    
    public static void main(String[] args) throws Exception {
        
        //加载A类对应的Class
        //Class<A> clazz = A.class;
        //此方法需要对类的全路径
        Class<?> clazz = Class.forName("com.use.A");
        
        //获取类对应的构造函数
        System.out.println("A 对应构造函数:");
        Constructor<?> cons[] = clazz.getConstructors();
        
        for(Constructor<?> con : cons){
            
            System.out.println(con.toString());
        }
        
        //获取A对应的变量
        System.out.println("A 对应变量: ");
        Field fields[] = clazz.getDeclaredFields();
        
        for(Field field: fields){
            
            System.out.println(field.toString());
        }
        
        //获取A对应的方法
        System.out.println("A对应的方法: ");
        Method[] methods = clazz.getDeclaredMethods();
        for(Method method: methods){
            
            System.out.println(method.toString());
        }
        
    }
}
    以下例子为对应通过反射使用构造函数生成对象:
   
 package com.use;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
 * 通过反射,使用构造函数生成对象
 * @author Mergades
 *
 */
public class ReflectionMethod {
    public ReflectionMethod() {
        System.out.println("Empty Constructor!");
    }
    public ReflectionMethod(Integer m) {
        System.out.println("Constructor with args: " + m);
    }
    public ReflectionMethod(Integer m, String s) {
        System.out.println("Constructor with double args: \n" + " m = " + m
                + ", s = " + s);
    }
    
    public static void main(String[] args) throws  Exception{
        //get Class
        Class<?> clazz = Class.forName("com.use.ReflectionMethod");
        //获取到对应类型的构造函数,通过构造Constructor的newInstance方法
        Constructor<?> cons[] = clazz.getConstructors();
         
        cons[2].newInstance();
        cons[1].newInstance(1);
        cons[0].newInstance(3, "abc");
        
        //通过Class对象对应的具体的Constructor,然后生成对象
        Constructor<?> c = clazz.getConstructor();
        c.newInstance();
        
        Constructor<?> cSingleArgs = clazz.getConstructor(Integer.class);
        cSingleArgs.newInstance(3);
        Constructor<?> cDoubleArgs = clazz.getConstructor(Integer.class, String.class);
        cDoubleArgs.newInstance(3, "s");
        
    }
}
 以下方式为通过反射调用对应对象的方法:
package com.use;
import java.lang.reflect.Method;
/**
 * 反射调用方法
 * @author Mergades
 *
 */
public class MethodInvoke {
    public void func1(){
        
        System.out.println("Function func1");
    }
    
    public void func2(int m){
        
        System.out.println("Function func2,args : " + m);
    }
    public void func3(int m, String s){
        
        System.out.println("Function func3, args : m :" + m + ", s:" + s);
    }
    
    public static void main(String[] args) throws Exception {
        
        Class<?> clazz = Class.forName("com.use.MethodInvoke");
        
        Object obj = clazz.getConstructor().newInstance();
        
        Method m1 = clazz.getMethod("func1");
        m1.invoke(obj);
        
        m1 = clazz.getMethod("func2", int.class);
        m1.invoke(obj, 3);
        
        m1 = clazz.getMethod("func3", int.class, String.class);
        m1.invoke(obj, 3, "s");
    }
}
3,反射与配置文件
    通过配置文件,使用反射生成不同的对象。
package com.properties;
/**
 * 图形接口 
 * @author Mergades
 *
 */
public interface IShape {
    /**
     * 输入方法
     * 
     * @return
     */
    boolean input();
    
    /**
     * 获取图形对应的面积
     * @return
     */
    float getArea();
}  
package com.properties;
/**
 * 图形处理类
 * @author Mergades
 *
 */
public class ShapeProc {
    /**
     * 图形对象
     */
    private IShape shape;
    
    public ShapeProc(IShape shape){
        
        this.shape = shape;
    }
    /**
     * 获取对应图形的面积
     * @return
     */
    public float process(){
        
        shape.input();
        float value = shape.getArea();
        return value;
    }
}
package com.properties;
 
import java.util.Scanner;
 
/**
* 圆
*
* @author Mergades
*
*/
public class Circle implements IShape {
 
float r;// 半径
 
@Override
public boolean input() {
 
System.out.println("请输入半径: ");
@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
r = s.nextFloat();
return true;
}
 
@Override
public float getArea() {
 
float s = (float) (Math.PI * r * r);
return s;
}
 
}
package com.properties;
 
import java.util.Scanner;
 
/**
* 矩形
* @author Mergades
*
*/
public class Rect implements IShape {
float width, height;
@Override
public boolean input() {
System.out.println("请输入宽、高 : ");
@SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
width = s.nextFloat();
height = s.nextFloat();
return true;
}
 
@Override
public float getArea() {
float s = width * height;
return s;
}
 
}

package com.properties;
 
import java.util.Properties;
 
public class Test {
 
public static void main(String[] args) throws Exception {
Properties p = new Properties();
p.load(new Test().getClass().getResourceAsStream("shape.properties"));
//System.out.println(p.getProperty("shape"));
String className = p.getProperty("shape");
IShape shape = null;
shape = (IShape) Class.forName(className).getConstructor().newInstance();
ShapeProc proc = new ShapeProc(shape);
float value = proc.process();
System.out.println(value);
}
}
对应目录结构:
bubuko.com,布布扣




































读书笔记_java设计模式深入研究 第二章 反射

标签:des   style   io   ar   color   os   使用   sp   java   

原文地址:http://blog.csdn.net/mergades/article/details/41656861

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!