日期:2014-05-20  浏览次数:20941 次

问一个关于java运用反射动态执行某个方法的问题。
//问题如下:
public class Users {
private String UserID;
private String UserName;

public String getUserName() {
return this.UserName;
}
public void setUserName(String userName) {
this.UserName = userName;
}
public String getUserID() {
return this.UserID;
}
public void setUserID(String userID) {
this.UserID = userID;
}

//提供类名称,方法名称,以及方法中参数的值,能否通过反射,执行某个方法?
//例如动态的执行“Users”类的“setUserID”方法,将this.UserID的值 设置为“administrator”?
public void execute(String ClassName,String MethodName,String ParameterValue)
{

}
}

------解决方案--------------------
/**
* Invokes accessible method of an object.
*
* @param c class that contains method
* @param obj object to execute
* @param method method to invoke
* @param paramClasses classes of parameters
* @param params parameters
? */
public static Object invoke(Class c, Object obj, String method, Class[] paramClasses, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Method m = c.getMethod(method, paramClasses);
return m.invoke(obj, params);
}

在不知道参数类型的情况下:
/**
* Returns classes from array of specified objects.
*/
public static Class[] getClasses(Object... objects) {
if (objects == null) {
return null;
}
Class[] result = new Class[objects.length];
for (int i = 0; i < objects.length; i++) {
if (objects[i] != null) {
result[i] = objects[i].getClass();
}
}
return result;
}
/**
* Invokes accessible method of an object without specifying parameter types.
* @param obj object
* @param method method of an object
* @param params method parameters
*/
public static Object invoke(Object obj, String method, Object[] params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Class[] paramClass = getClasses(params);
return invoke(obj, method, paramClass, params);
}

------解决方案--------------------
可以的,但是你要保证你传递的参数和要执行的方法的参数匹配。
------解决方案--------------------
完全可以的,但是你需要知道参数的类型和个数。如果参数类型和个数不匹。
写了一段例子,希望对你有帮助
Java code

public class Test {
    public static void main(String[] args) throws Exception{
        List list = new ArrayList();
        Class c = Class.forName("java.util.ArrayList");
        Method method = c.getDeclaredMethod("add", new Class[]{Object.class});
        method.invoke(list, new Object[]{new Integer(100)});
        System.out.println(list.get(0));
    }
}

------解决方案--------------------
参考如下代码:
Java code

public class Users {

    private String UserID;
    private String UserName;

    public String getUserName() {
        return this.UserName;
    }

    public void setUserName(String userName) {
        this.UserName = userName;
    }

    public String getUserID() {
        return this.UserID;
    }

    public void setUserID(String userID) {
        this.UserID = userID;
    }

}