//用 反射,下面是示例代码。package mytest;import java.lang.reflect.*;
import java.lang.*;public class ReflectTest { private String str; public void setStr( String theStr){ this.str = theStr;} public String getStr(){ return this.str;} public ReflectTest() {}
public ReflectTest( String theStr){ this.str = theStr;} public void printStr(){
System.out.println(" invoke this method start");
System.out.println(" theStr ="+this.str);
System.out.println(" this invoke is end");
} public static void main(String[] args) {
ReflectTest reflectTest1 = new ReflectTest( " aaa");
Class reflectClass = reflectTest1.getClass();
// that is your request: try {
Method theSpecialMethod = reflectClass.getMethod("printStr",null);
Object theSpecialRerurnValue = theSpecialMethod.invoke( reflectTest1,null);
System.out.println(" theSpecialRerurnValue = "+ theSpecialRerurnValue);
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}catch (IllegalArgumentException ex) {
ex.printStackTrace();
}catch (InvocationTargetException ex) {
ex.printStackTrace();
}catch (NoSuchMethodException ex) {
ex.printStackTrace();
}catch (SecurityException ex) {
ex.printStackTrace();
}
}
import java.lang.*;public class ReflectTest { private String str; public void setStr( String theStr){ this.str = theStr;} public String getStr(){ return this.str;} public ReflectTest() {}
public ReflectTest( String theStr){ this.str = theStr;} public void printStr(){
System.out.println(" invoke this method start");
System.out.println(" theStr ="+this.str);
System.out.println(" this invoke is end");
} public static void main(String[] args) {
ReflectTest reflectTest1 = new ReflectTest( " aaa");
Class reflectClass = reflectTest1.getClass();
// that is your request: try {
Method theSpecialMethod = reflectClass.getMethod("printStr",null);
Object theSpecialRerurnValue = theSpecialMethod.invoke( reflectTest1,null);
System.out.println(" theSpecialRerurnValue = "+ theSpecialRerurnValue);
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}catch (IllegalArgumentException ex) {
ex.printStackTrace();
}catch (InvocationTargetException ex) {
ex.printStackTrace();
}catch (NoSuchMethodException ex) {
ex.printStackTrace();
}catch (SecurityException ex) {
ex.printStackTrace();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货