Java.lang.reflect.Method invoke方法の例
2047 ワード
プログラム内のプロファイルには、エンティティオブジェクトのget、set方法の記述があり、invoke()方法を適用してエンティティオブジェクトを呼び出すmethod方法があります。 return m_oGetter.invoke(oSrc,null)//oSrcは実体オブジェクトであり,Method m_o Getterここのm_oGetterは、プロキシのインスタンス(oSrc)でのアップグレードのためのインターフェース方法に対応するMethodの例であり、以下のコード例を参照する。
import java.lang.reflect.Method;
public class InvokeMethods {
public static void main(String[] args){
Employee emp = new Employee();
Class cl = emp.getClass();
///getClass emp ,Class
///Class , ,
/// , !
try{
///getMethod
/// Employee setAge ,
// , ! null
///
Method sAge = cl.getMethod("setAge",new Class[] {int.class});
Method gAge = cl.getMethod("getAge",null);
Method pName = cl.getMethod("printName",new Class[] {String.class});
/** * invoke */
Object[] args1 = { new Integer(25) };
//
//emp
sAge.invoke(emp, args1);
Integer AGE = (Integer)gAge.invoke(emp, null);
int age = AGE.intValue();
System.out.println("The Employee Age is: "+age);
Object[] args3 = {new String("Jack") };
pName.invoke(emp, args3);
}
catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
class Employee{
//
public Employee()
{
age = 0;
name = null;
}
//
public void setAge(int a)
{
age = a;
}
//
public int getAge()
{
return age;
}
//
public void printName(String n)
{
name = n;
System.out.println("The Employee Name is: "+name);
}
private int age;
private String name;
}