0

私はJavaが初めてなので(〜10日)、私のコードはおそらくかなり悪いですが、ここに私が持っているものがあります:

ArgsDataHolder argsData = new ArgsDataHolder();  // a class that holds two
                                                 // ArrayList's where each element
                                                 // representing key/value args
Class thisArgClass;
String thisArgString;
Object thisArg;

for(int i=2; i< argsString.length; i++) {
    thisToken = argsString[i];
    thisArgClassString = getClassStringFromToken(thisToken).toLowerCase();
    System.out.println("thisArgClassString: " + thisArgClassString);
    thisArgClass = getClassFromClassString(thisArgClassString);

    // find closing tag; concatenate middle
    Integer j = new Integer(i+1);
    thisArgString = getArgValue(argsString, j, "</" + thisArgClassString + ">");

    thisArg = thisArgClass.newInstance();
    thisArg = thisArgClass.valueOf(thisArgString);
    argsData.append(thisArg, thisArgClass);
}

ユーザーは基本的に、一連のキー/値引数を次の形式でコマンド プロンプトに入力する必要があり<class>value</class>ます<int>62</int>。この例を使用すると、thisArgClassは と等しくなりInteger.classthisArgStringは "62" を読み取る文字列になり、thisArg62 に等しい Integer のインスタンスになります。

試してみましたが、オブジェクトの特定のサブクラスのメソッドに過ぎthisArg.valueOf(thisArgString)ないと思います。valueOf(<String>)なんらかの理由で、 thisArg を thisArgClass にキャストできないようです (次のように: thisArg = (thisArgClass)thisArgClass.newInstance();、その時点valueOf(<String>)でアクセス可能になるはずです。

これを行うための素晴らしくクリーンな方法が必要ですが、現時点では私の能力を超えています。動的に型指定されたオブジェクト (Integer、Long、Float、Double、String、Character、Boolean など) に読み込まれた文字列の値を取得するにはどうすればよいですか? それとも、私がこれを考えすぎているだけで、Java が変換してくれるのでしょうか? :混乱している:

4

2 に答える 2

1

thisArg を thisArgClass にキャストできないようです (次のように: thisArg = (thisArgClass)thisArgClass.newInstance();,

最初に初期化する必要があるため、これはこのようには機能しません。これthisArgClassにより、コンパイル時エラーが発生します。コードを次のように変更します。

Class thisArgClass = null;
try {
    Object thisArg = thisArgClass.newInstance();
} catch (InstantiationException ex) {
    Logger.getLogger(Test3.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    Logger.getLogger(Test3.class.getName()).log(Level.SEVERE, null, ex);
}

これがあなたを助けることを願っています。

于 2012-06-04T04:29:56.407 に答える
1

ここにはいくつかの間違いがあります。thisArgClass正しく設定されていると仮定します。あなたの例では、が含まれますInteger.class。オブジェクトで呼び出すnewInstance()には、クラスに引数なしのコンストラクターが必要です。Classにはそのようなコンストラクターがないため、より遠回りの方法を使用して既存のコンストラクターの 1 つを呼び出す必要があります。ClassInteger

Constructor<Object> c = thisArgClass.getConstructor(String.class);
Object i = c.newInstance(thisArgString);

実行時までオブジェクトの実際の型がわからないため<Object>、値を使用する前に、結果を使用して目的の型にキャストする必要があります。

于 2012-06-04T04:44:00.333 に答える