java_反射

package com.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Field;



public class Test {

	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static void main(String[] args) throws Exception, ClassNotFoundException, InstantiationException, IllegalAccessException {
		// TODO Auto-generated method stub
		Class
   
    c = Class.forName("com.test.Word");
		//Word wd = (Word)c.newInstance();
		//获取成员方法,包含父类的方法
		Method [] ms = c.getMethods();	//c.getDeclaredMethods();只获取当前类自身的方法
		for(int msNum=0; msNum < ms.length; msNum++){
			//方法的返回值类型
			Class returnType = ms[msNum].getReturnType();
			System.out.print(returnType.getName() + " ");
			//方法名
			System.out.print(ms[msNum].getName() + "(");
			//参数
			Class[] paramsType = ms[msNum].getParameterTypes();			
			for(Class class1 : paramsType){
				System.out.print(class1.getName() + ",");
			}
			System.out.println(")");
		}
		//成员方法
		useMethod(c);
		//成员变量
		getFields(c);
		
		//同理获取构造方法	
		Constructor[] cs = c.getConstructors();
		for(Constructor constructor : cs){
			//构造方法名
			System.out.print(constructor.getName() + "(");
			//获取参数列表
			Class[] paramType = constructor.getParameterTypes();
			for(Class class2 : paramType){
				System.out.print(class2.getName() + ",");
			}
			System.out.println(")");
		}
	}
	/**
	 * 获取成员变量
	 * @param c
	 */
	public static void getFields(Class
   
    c) {
		//获取成员变量
		Field[] field = c.getFields();
		for(Field fs : field){
			//成员变量类型的类类型
			Class fieldType = fs.getType();
			String typeName = fieldType.getName();
			//成员变量的名称
			String fieldName = fs.getName();
			System.out.println(typeName + " " + fieldName);
		}
	}
	/**
	 * 调用成员方法
	 * @param c
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 */
	public static void useMethod(Class
   
    c) throws InstantiationException,
			IllegalAccessException, NoSuchMethodException,
			InvocationTargetException {
		//通过反射调用方法
		Word word = (Word)c.newInstance();
		Method method = c.getMethod("wordTest", new Class[]{String.class, String.class});
		Object obj = method.invoke(word, new Object[]{"hello","word"});
		System.out.println("main方法:" + obj.toString());
	}

}

class Word{
	public static String VALUE = "HELLO WORLD";
	public String wordTest(String str1, String str2){
		System.out.println(str1 + ",wordTest ..." + str2);
		return str1 + "," + str2;
	}
	public Word(String str1, String str2){
		System.out.println("word string two");
	}
	public Word(){
		System.out.println("===========");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值