java reflect 的使用事例_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java reflect 的使用事例

java reflect 的使用事例

 2011/10/14 9:38:49  nello  http://technique-digest.iteye.com  我要评论(0)
  • 摘要:packagecommon;importjava.text.SimpleDateFormat;importjava.util.Date;publicclassDemo{publicStringname;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicStringsayHello(){return"hello";}publicStringsayHello
  • 标签:使用 Java
package common;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo {
	public String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String sayHello() {
		return "hello";
	}
	
	public String sayHello(String name) {
		return name + ", hello";
	}
	
	public String sayHello(String name, Date date) {
		return name + ", hello at " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
	}

}

package reflect;

import java.util.Date;
import common.Demo;

public class Test1 {
	public static void main(String[] args) {
		try {
			Class<?> clazz = Class.forName("common.Demo");
			Demo demo = (Demo) clazz.newInstance();
			demo.setName("java reflect");
			System.out.println(demo.getName());
			System.out.println(demo.sayHello());
			System.out.println(demo.sayHello("java world"));
			System.out.println(demo.sayHello("java world", new Date()));
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}

package reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

public class Test2 {
	public static void main(String[] args) {
		try {
			Class<?> clazz = Class.forName("common.Demo");
			Object obj = clazz.newInstance();
			
			Field f = clazz.getField("name");
			f.set(obj, "java");
			
			Method m0 = clazz.getMethod("getName", new Class[0]);
			System.out.println(m0.invoke(obj, new Object[0]).toString());
			
			
			Method m1 = clazz.getMethod("sayHello", new Class[0]);
			System.out.println(m1.invoke(obj, new Object[0]).toString());
			
			Method m2 = clazz.getMethod("sayHello", new Class[]{ String.class });
			System.out.println(m2.invoke(obj, new Object[] { "java world" }).toString());
			
			Method m3 = clazz.getMethod("sayHello", new Class[]{ String.class, Date.class });
			System.out.println(m3.invoke(obj, new Object[] { "java world", new Date() }).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



发表评论
用户名: 匿名