请问怎么样写一个比较通用的反射程序来调用方法 譬如我这里有两个类 怎么调用他们的方法
class Student{
String name;
public Student(String name){
this.name=name;
}
public void study(String course){
System.out.println(name+" studies "+course);
}
}class Teacher{
String name;
public Teacher(){
System.out.println("Create Teacher");
}
public Teacher(String name){
this.name=name;
}
public void teach(String course){
System.out.println(name+" teachs "+course);
}
}

解决方案 »

  1.   

    Class.forName("fullClassName").getMethod("methodName",new Class[]{Param1.class,param2.class}).invoke(Class.forName("xxxx").newInstance(),new Object[]{param1,param2});
      

  2.   

    import java.lang.reflect.*;
    public class TestReflect {
    public static void main(String[] args) throws Exception{
    // step1 get Class Object
    Class c=Class.forName(args[0]);//args[0]是类名
    // step2 get Constructor Object
    Class[] parameters={String.class};
    Constructor con=c.getConstructor(parameters);
    // step3 get Object
    Object[] os={args[1]};//args[1]是构造方法中的参数
    Object o=con.newInstance(os);//Constructor
    //step4 get Method Object
    Method m=c.getMethod(args[2],parameters);//args[2]是方法名
    //step5 invoke method
    Object[] os2={args[3]};//args[3]是方法参数
    m.invoke(o,os2);

    }
    }
    //敲下面的就OK了 
    //java TestReflect Student Stephen study Java
    //希望你可以看懂 这东西确实不好理解 挺抽象的
    //顺便问下 你用反射干什么?
      

  3.   

    写个static函数,(注这个不是用来调用static函数的如果要支持static,需要里面判断扩充下)
    public static Object ReflectMethod(Object obj,Method m,Object params[])
    {
    Assert(ojb!=null);
    if(params == null)
    {
    params= new Object[0];
    }
    Class paramTypes[]= new Class[params.length];
    Object objReturn = null;

    for(int i=0;i<paramTypes.length;i++)
    {
    paramTypes[i] = params[i].getClass();
    }
    try
    {
    Method m = c.getMethod("methodName",paramTypes);
    try
    {
    objReturn = m.invoke(obj,params);
    }catch(IllegalAccessException iae)
    {
    iae.printStackTrace();
    }
    catch(IllegalArgumentException iarge)
    {
    iarge.printStackTrace();
    }
    catch(Exception e)
    {
    e.getCause().printStackTrace();
    }

    }
    catch(NoSuchMethodException nsme)
    {
    nsme.printStackTrace();
    }
    return objReturn;
    }
      

  4.   

    上面写错了
    重新贴一下
    写个static函数,(注这个不是用来调用static函数的如果要支持static,需要里面判断扩充下)
    public static Object ReflectMethod(Object obj,String methodName,Object params[])
    {
    Assert(ojb!=null);
    Class c = obj.getClass();
    if(params == null)
    {
    params= new Object[0];
    }
    Class paramTypes[]= new Class[params.length];
    Object objReturn = null;

    for(int i=0;i<paramTypes.length;i++)
    {
    paramTypes[i] = params[i].getClass();
    }
    try
    {
    Method m = c.getMethod(methodName,paramTypes);
    try
    {
    objReturn = m.invoke(obj,params);
    }catch(IllegalAccessException iae)
    {
    iae.printStackTrace();
    }
    catch(IllegalArgumentException iarge)
    {
    iarge.printStackTrace();
    }
    catch(Exception e)
    {
    e.getCause().printStackTrace();
    }

    }
    catch(NoSuchMethodException nsme)
    {
    nsme.printStackTrace();
    }
    return objReturn;
    }
    }
      

  5.   

    使用方式就是建立一个类Reflector把上面的函数放进去,如下使用Reflector.ReflectMethod(对象名,函数名,函数各参数数组)
    假设有student对象实列
    Reflector.ReflectMethod(student,"study",new Object[]{"数学"},这个就会调用study方法de
      

  6.   

    这是以前写的不怎么好,凑合能用,lz可以参拷下./**
    * 主要用与执行类
    */
    public class ClassParseAdp {
    /**
     * 创建实例
     * @param cb
     * @return
     * @throws NoSuchMethodException 
     * @throws SecurityException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     * @throws IllegalArgumentException 
     */
    public static Object createInstance(ClassBean cb) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
    Object obj = null;
    Class c = null;
    Constructor constr = null;

    c = toClass(cb.getClassName() );
    constr = c.getConstructor(cb.getTypes() );
    obj = constr.newInstance(cb.getParas() );
    if(isInstance(c, obj) ){
    return new RuntimeException("object not instanceof Class");
    }

    return obj;
    }
    /**
     * 同execute(String className, String methodName)
     */
    public static Object execute(Class c, Method method){
    return execute(c.getName(), method.getName());
    }
    /**
     * <p>执行</p>
     * 根据className实例化一个类,并运行名为methodName的方法
     * @param className 类名
     * @param methodName 方法名
     * @return 方法的返回值<br>
     * 注:如果此方法无返回值,则返回null
     */
    public static Object execute(String className, String methodName){
    return execute(className, methodName, new Object[0]);
    }
    /**
     * <p>执行方法并返回方法的返回值</p>
     * 注:<br>
     * <p>cs的大小必需与objs的大小相等</p>
     * <p>如果方法的返回值是一个基本类型(如:int.double),则自动把其变为包装类型(如:Integer.Double.Boolean)</p>
     * <p>同样如果参数为一个基本类型,则应用包装类将值包装,并指出Class</p>
     * @param className 类名
     * @param methodName 方法名
     * @param cs 参数类型
     * @param paras 参数列表
     * @return 方法的返回值
     */
    public static Object execute(String className, String methodName, Class[] cs, Object[] paras){
    Object reObj = null;
    Object obj = null;
    Method method = null;

    if( (null != cs && null != paras) && (cs.length != paras.length) ){
    throw new RuntimeException("data type not matching");
    }
    try{
    obj = Class.forName(className).newInstance();
    method = obj.getClass().getMethod(methodName, cs);
    reObj = method.invoke(obj, paras);
    }catch(Exception e){
    throw new RuntimeException(e);
    }

    return reObj;
    }
    /**
     * <p>执行方法并返回方法的返回值</p>
     * @param className 类名
     * @param methodName 方法名
     * @param objs 方法参数列表
     * @return 方法的返回值
     */
    public static Object execute(String className, String methodName, Object[] objs){
    return execute(className, methodName, toClasses(objs), objs);
    }
    /**
     * 执行
     * @param cb 
     * @return 方法的返回值
     * @throws RuntimeException -如果返回对象不是返回类型的实例时抛出
     */
    public static Object execute(ClassBean cb){
    Object reObj = null;
    Class c = toClass(cb.getClassName());

    if(null == cb){
    return null;
    }
    reObj = execute(cb.getClassName(), cb.getMethodName(),
    cb.getTypes(), cb.getParas());

    if(isInstance(c, reObj) ){
    throw new RuntimeException();
    }

    return reObj;
    }

    /**
     * 参数obj是否为c的实例
     * @param c
     * @param obj
     * @return 
     */
    public static boolean isInstance(Class c, Object obj){
    boolean yes = false;

    if(null != c && null != obj){
    if(c.isInstance(obj)){
    yes = true;
    }
    }

    return yes;
    }

    /**
     * 将Class类转换为Object
     * @param cs
     * @return
     */
    public static Object toObject(Class cs){
    Object obj = null;
    try {
    obj = cs.newInstance();
    } catch (Exception e) {
    e.printStackTrace();
    }
    return obj;
    }

    /**
     * 将类名字符串转化为Class类
     * @param className
     * @return
     */
    public static Class toClass(String className){
    Class c = null;
    try {
    if("int".equals(className)){
    c = int.class;
    }else if("long".equals(className)){
    c = long.class;
    }else if("float".equals(className)){
    c = float.class;
    }else if("double".equals(className)){
    c = double.class;
    }else if("char".equals(className)){
    c = char.class;
    }else if("boolean".equals(className)){
    c = boolean.class;
    }else{
    c = Class.forName(className);
    }
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return c;
    }

    /**
     * 将Object[]转换为Class[]
     * @param objs
     * @return
     */
    public static Class[] toClasses(Object[] objs){
    Class[] cs = new Class[null == objs? 0: objs.length];
    for(int i = 0; i < cs.length; i++){
    cs[i] = objs[i].getClass();
    }
    return cs;
    }
    }
    /**
     * 类
     * <p>描述一个类</p>
     * @author sl
     *
     */
    public class ClassBean {
    //类名
    private String className;
    //方法名
    private String methodName;
    //返回类型
    private String returnType;
    //参数类型
    private Class[] paraTypes;
    //参数列表
    private Object[] paras;

    public ClassBean(){
    this.className = null;
    this.methodName = null;
    this.returnType = null;
    this.paraTypes = null;
    this.paras = null;
    }

    public ClassBean(String className, String methodName, String returnType){
    this.className = className;
    this.methodName = methodName;
    this.returnType = returnType;
    }
    public ClassBean(String className, String methodName, String returnType,
    Class[] paraTypes, Object[] paras){
    this.className = className;
    this.methodName = methodName;
    this.returnType = returnType;
    this.paraTypes = paraTypes;
    this.paras = paras;
    }

    public String getClassName() {
    return className;
    }
    public void setClassName(String className) {
    this.className = className;
    }
    public String getMethodName() {
    return methodName;
    }
    public void setMethodName(String methodName) {
    this.methodName = methodName;
    }
    public Object[] getParas() {
    return paras;
    }
    public void setParas(Object[] paras) {
    this.paras = paras;
    }
    public String getReturnType() {
    return returnType;
    }
    public void setReturnType(String returnType) {
    this.returnType = "".endsWith(returnType) ? null: returnType;
    }
    public Class[] getTypes() {
    return paraTypes;
    }
    public void setTypes(Class[] types) {
    this.paraTypes = types;
    }
    }