リフレクションを用いてメンバを直接操作する演習で、下記コード★★★★★部のnewInstance()の引数256の意味がわかりません。演習の前ではnewInstance()は引数なしでnewする。と書いてあり、ググってみてもイマイチ理解ができません。数値を変えても実行時に特に変化は見られず何をしているのか、、、どなたか解説していただけないでしょうか。
public class RefSample { public int times = 0; public RefSample(int t) { this.times = t; } public void hello(String msg) { this.hello(msg,this.times); } public void hello(String msg,int t) { System.out.println("Hello," + msg + "x" + t); } } import java.lang.reflect.*; public class Main { public static void main(String[] args) throws Exception { // TODO 自動生成されたメソッド・スタブ Class clazz = RefSample.class; //RefSampleより情報を取得する //引数一つのコンストラクタを取得し、インスタンスを生成する Constructor<?> cons = clazz.getConstructor(int.class);/*public void hello(String msg) { this.hello(msg,this.times); }*/ ★★★★★ RefSample rs = (RefSample) cons.newInstance(256); //pubフィールドに関するFieldを取得して読み書き Field f = clazz.getField("times"); f.set(rs, 2); //rsのtimesに代入 System.out.println(f.get(rs));//rsのtimesを取得 //引数二つのhelloメソッドを取得して呼び出す Method m = clazz.getMethod("hello", String.class,int.class); m.invoke(rs, "reflection!",128);/*public void hello(String msg,int t) { System.out.println("Hello," + msg + "x" + t); */ //クラスやメソッドへの修飾(publicやfinalの有無)を調べる boolean pubc = Modifier.isPublic(clazz.getModifiers()); boolean finm = Modifier.isFinal(clazz.getModifiers()); System.out.println(pubc); System.out.println(finm); } }

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/01/28 04:21