Created
December 3, 2013 03:43
-
-
Save seraphy/7763547 to your computer and use it in GitHub Desktop.
Expressを使ってリフレクションを直接使うよりも簡単にメソッド名でオブジェクト(Java Beans)にアクセスする方法の例.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.seraphyware.javalangtest; | |
import java.beans.Expression; | |
/** | |
* リフレクションを直接使うよりも簡単にメソッド名で | |
* オブジェクトにアクセスする方法の例.<br> | |
*/ | |
public class ExpressionTest { | |
private long val = 1234; | |
public long getVal() { | |
return val; | |
} | |
public void setVal(long val) { | |
this.val = val; | |
} | |
public static long now() { | |
return System.currentTimeMillis(); | |
} | |
public void sayHello() { | |
System.out.println("hello!"); | |
} | |
public void sayHello(String msg) { | |
System.out.println("hello! " + msg); | |
} | |
public static void main(String[] args) throws Exception { | |
// クラスメソッドへのアクセス方法 | |
Class<?> cls = Class.forName("jp.seraphyware.javalangtest.ExpressionTest"); | |
Expression expNow = new Expression(cls, "now", null); | |
System.out.println("★"); | |
long retNow = (Long) expNow.getValue(); | |
System.out.println("retNow=" + retNow); | |
// インスタンスメソッドへのアクセス | |
Object inst = new ExpressionTest(); | |
// 値の設定 | |
// メソッドの呼び出しは、すべてgetValueで行う. | |
// 値の設定であってもgetValueメソッドを呼び出す必要がある. | |
// (setValueを呼び出すと次のgetValueはメソッドを呼び出さずに、その値を返す) | |
Expression expSetVal = new Expression(inst, "setVal", new Object[]{Long.valueOf(1212)}); | |
System.out.println("★"); | |
System.out.println("expSetVal=" + expSetVal.getValue()); | |
// 値の読み込み | |
Expression expGetVal = new Expression(inst, "getVal", null); | |
System.out.println("★"); | |
long retGetVal = (Long) expGetVal.getValue(); | |
System.out.println("expGetVal=" + retGetVal); | |
// メソッドの呼び出し1 | |
Expression expSayHello1 = new Expression(inst, "sayHello", null); | |
System.out.println("★"); | |
expSayHello1.getValue(); | |
// 引数つきメソッドの呼び出し2 | |
Expression expSayHello2 = new Expression(inst, "sayHello", new Object[]{"FooBar"}); | |
System.out.println("★"); | |
expSayHello2.getValue(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
★ | |
retNow=1386329246598 | |
★ | |
expSetVal=null | |
★ | |
expGetVal=1212 | |
★ | |
hello! | |
★ | |
hello! FooBar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment