zoukankan      html  css  js  c++  java
  • Java 反射经常用法演示样例

    <pre name="code" class="java">import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    class Point{
    	int x;
    	private int y;
    	
    	public Point(){
    		x = 1;
    		y = 2;
    	}	
    	
    	public void setX(int x) {
    		this.x = x;
    	}
    
    	public void setY(int y) {
    		this.y = y;
    	}
    
    	private Point(int x){
    		this();
    		this.x = x;
    	}
    	
    	public Point(int x, int y) {
    		super();
    		this.x = x;
    		this.y = y;
    	}
    	
    	public void printPoint(){
    		System.out.println("x = " + x + " , y = " + y);
    	}
    }
    
    public class ReflectTest2 {
    
    	public static void main(String[] args) throws Exception {
    		
    		//使用第一种方法创建对象
    		Class cls1 = Class.forName("Point");
    		Constructor con1 = cls1.getConstructor(int.class,int.class);
    		Point p1 = (Point) con1.newInstance(5,6);
    		p1.printPoint();
    		
    		//使用另外一种方法创建对象
    		Class cls2 = Point.class;
    		Point p2 = (Point) cls2.newInstance();//无參构造函数
    		p2.printPoint();
    		
    		//使用第三种方法创建对象
    		Class cls3 = p1.getClass();
    		//使用p1对象的setX方法将x值改动为10
    		Method m1 = cls3.getMethod("setX", int.class);
    		m1.invoke(p1, 10);
    		p1.printPoint();
    		
    		/*
    		 * Note:
    		 * getDeclaredConstructor能够返回指定參数的构造函数,
    		 * 而getConstructor仅仅能放回指定參数的public的构造函数 
    		 * */		
    		Constructor con2 = cls3.getDeclaredConstructor(int.class);
    		//訪问私有变量、函数须要设置accessible
    		con2.setAccessible(true);
    		Point p4 = (Point) con2.newInstance(3);
    		p4.printPoint();
    		
    		//Field f1 = cls3.getField("y");//error
    		Field f1 = cls3.getDeclaredField("y");
    		f1.setAccessible(true);
    		//获取p1的y值
    		System.out.println(f1.get(p1));
    	}
    
    }
    


    
       
    
  • 相关阅读:
    股票交易接口
    股票自动买卖
    安信证券接口的demo做得不好。
    MEF bug? 无法加载外部的DLL
    如何移植行情软件的指标到千发股票自动交易软件?
    股票策略交易
    博客园自动关注病毒 只活了一小会儿。
    Float 运算的怪异性
    文件大小和占用空间为何不一样
    做最好的自己
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6985848.html
Copyright © 2011-2022 走看看