您的位置:首页 > 编程语言 > Java开发

java_反射

2016-08-30 17:26 113 查看
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("===========");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: