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”的字符串,并且thisArg将是等于 62 的 Integer 实例。

我试过了thisArg.valueOf(thisArgString),但我猜valueOf(<String>)只是Object的某些子类的一种方法。无论出于何种原因,我似乎无法将 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对象,类必须有一个无参数的构造函数。类Integer没有这样的构造函数,因此您必须使用更迂回的方法调用现有构造函数之一:

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

由于您直到运行时才知道对象的实际类型,因此您必须<Object>在使用该值之前使用并将结果转换为所需的类型。

于 2012-06-04T04:44:00.333 回答