Java的反射(reflection)_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java的反射(reflection)

Java的反射(reflection)

 2015/2/11 12:45:09  小熊座  程序员俱乐部  我要评论(0)
  • 摘要:反射的语句非常简单,例如以下这句就可以根据Dog的类名来创建Dog对象:Dogdog=(Dog)(Class.forName("reflection.Dog").newInstance())全例:Dog类:packagereflection;publicclassDog{privateStringname;privateintage;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;
  • 标签:Java 反射

反射的语句非常简单,例如以下这句就可以根据Dog的类名来创建Dog对象:

class="java" name="code">Dog dog = (Dog) (Class.forName("reflection.Dog").newInstance())

?

全例:

Dog类:

package reflection;

public class Dog {

	private String name;
	private int age;

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

?反射类:

package reflection;

public class ReflectionTest {

	/**
	 * @param args
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static void main(String[] args) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException {
		Dog dog = (Dog) (Class.forName("reflection.Dog").newInstance());
		dog.setName("wang");
		dog.setAge(1);
		System.out.println("My dog is:" + dog.getName() + ", he is "
				+ dog.getAge() + " years old.");
	}

}

?结果打印:

My dog is:wang, he is 1 years old.

发表评论
用户名: 匿名