java反射实例

package org.hml.okok;
public class okokokoko {
public String sayHello(String str) {
return str;
}
}

//用反射的方式调用

package org.hml.okok;


import java.lang.reflect.Method;


public class testClass {

public static void main(String[] args) {

// TODO Auto-generated method stub

Class<?> c1=null;

try {

c1=Class.forName("org.hml.okok.okokokoko");

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

Method m=c1.getMethod("sayHello",String.class);

String str=(String) m.invoke(c1.newInstance(),"hello");

System.out.println(str);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 


你可能感兴趣的:(java反射)