import java.lang.reflect.*;
class animal{
private int value;
private String str;
public animal(int val, String s ){
value = val;
str = s;
System.out.println("constructor ok..."+value+" " + s );
}
public void print (int val)
{
System.out.println("method ok...val: " + val);
}
public static void main(String argc[])
{
System.out.println("main ok");
}
}
class Person {}
public class mehtodTest {
public static void main(String [] argc) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
Class > classType = Class.forName("Test1.animal");
//Constructor> con = classType.getConstructor(Integer.TYPE, String.class);
//
//Object obj =con.newInstance( 30, "hello");
//animal anim = (animal) obj;
//以上实例化可以用下面一句语句写
Object obj = classType.getConstructor(int.class, String.class).newInstance(30, "hello");
Method mtd = classType.getMethod("print", int.class);
Object mtdPrint = mtd.invoke(obj, 15); //invoke普通方法需要实例化的类作为第一个参数
Method mtd2 = classType.getMethod("main", String[].class);
String[] s = null;
mtd2.invoke(null, (Object)s); //invoke静态(main也是静态)方法第一个参数传null,不需要实例化
/**这里直接传s数组是不对的,会出现参数个数不正确的错误,应为JDK会自动把数组元素打开
* 这样就包含的很多的元素,所以前面加个(Object)告诉编译器,这是一个对象,不要拆箱
*/
}
}
output:
constructor ok...30 hello
method ok...val: 15
main ok