-2

私がしようとしているものの通常の形はこれです。

MyClassFacadeLocal cls = new MyClassFacadeLocal();
List allMyClass = cls.findAll();
Iterator it = allMyClass.iterator();
while(it.haxNext()) {
    MyClass Obj = (MyClass)it.next();
    out.println(obj.getTitle());
}

さて、私が作成している問題は、このいくつかのケースを処理できるグローバル メソッドです。このために、エンティティ クラス名、メソッド名、およびメソッドによって返されるリストを渡し.findAll()ます。反射を使用してこれを解決する方法。私が試したことは本当に大まかで、もちろんうまくいきませんでした。

List allMyClass; //I will have passed this before
Iterator it = allMyClass.iterator();
while(it.hasNext()) {

    try {
        Class<?> c = Class.forName(this.getEntityClassName());
        c.cast(it.next());
        Method method = c.getDeclaredMethod("getTitle");
        String title = method.invoke(c, null).toString();
    } catch(Exception e) {
    }

}

与えます:"object is not an instance of declaring class"エラー。しかし、これは使用上の欠陥であると確信しています。

4

3 に答える 3

0

本当に、それをするためにリフレクションを使うべきではありません。すべてのエンティティに、次のgetTitle()メソッドを使用して共通のインターフェースを実装させます。

public interface HasTitle {
    public String getTitle();
}

public class MyClass1 implements HasTitle {
    // ...

    @Override
    public String getTitle() {
        return this.title;
    }
}

public class MyClass2 implements HasTitle {
    // ...

    @Override
    public String getTitle() {
        return this.title;
    }
}

...

/**
 * This method can be invoked withg a List<MyClass1> or with a List<MyClass2>
 * as argument, since MyClass1 and MyClass2 both implement HasTitle
 */
public void displayTitles(List<? extends HasTitle> entities) {
    for (HasTitle entity : entities) {
        out.println(entity.getTitle();
    }
}
于 2012-07-02T07:53:03.920 に答える
0

私が見る最初の欠点は、あなたが割り当てていないことです

c.cast(it.next());

新しい変数に。

于 2012-07-02T07:43:33.227 に答える
0

Class.forNameあなたのコードは、間違ったリフレクション メソッドを使用してあまりにも多くの作業をgetDeclaredMethod行っています。つまり、継承されたメソッドが考慮されていません。このc.cast行は何もしません。オブジェクトがそれ自身のクラスのインスタンスであることを表明するだけです。

次のコードを使用します。

public static void printProp(List<?> xs, String methodName) {
  try {
    for (Object x : xs)
      System.out.println(x.getClass().getMethod(methodName).invoke(x));
  } catch (Exception e) { throw new RuntimeException(e); }
}
于 2012-07-02T07:59:05.187 に答える