现在的位置: 首页 > 综合 > 正文

Java 反射

2013年08月02日 ⁄ 综合 ⁄ 共 1075字 ⁄ 字号 评论关闭

 

import java.lang.reflect.*;
import java.util.*;
class PPerson 
{	
	public static String  name;// 静态成员
	public final int MAX ;    //  常量在定义的时候可以直接初始化,也可以 在构造函数里面初始化
	public int age ;
	public PPerson()
	{
		name = "google";
		age = 10;
		MAX = 100;
	}
	public PPerson(int d )
	{
		MAX =2;
	}
	
	public String getName()
	{
		return this.name;
	}
	public int  getAge()
	{
		return this.age;
	}
	public static void Say()
	{
		System.out.println("I'm Say...");
	}
}
public class Reflect {
	
	public static void main(String args[]) throws Exception
	{
			Class pp = Class.forName("PPerson");
			
			System.out.println(pp.getName()); //得到类的名字
			Field field[] = pp.getFields();  //得到字段
			System.out.println(Arrays.toString(field));
			Method method[] = pp.getMethods();// 得到 方法
			System.out.println(Arrays.toString(method));
			Constructor cons[] = pp.getConstructors();
			for(Constructor c : cons)
				System.out.println(c);
			
			PPerson person = (PPerson) pp.newInstance();
			person.Say();
			
	}
}


			/*
			 * 										Java 反射机制
			 * 
			 * 		1.  先得到该类的Class ,然后利用Class 里面的方法
			 * 					得到 Class 对象的方法有:
			 * 										String.class 
			 * 										new String().getClass()
			 * 										Class.forName("String")
			 * 		2.Class 类里面的方法,也是利用 得到 的Class对象来进行一个类型的查询
			 * 				getName 
			 * 				getFields
			 * 				getMethods
			 * 				getConstructors
			 * 				newInstance
			 * */

http://hi.baidu.com/changsheng/blog/item/87353af3d6fba350352accd6.html

【上篇】
【下篇】

抱歉!评论已关闭.