开发者

Java Reflection passing parameters

HI,

I have methods each of them requires integer ,string respectively. I read the inputs from my xml file. I will not be aware of what the type of inputs it will be. I am using reflection to invoke the method. I read the xml and store it as string. I invoke the method by passing in the parameter. One of the method expects an integer, but I pass in string. When I try to do the getType and cast, it is开发者_高级运维 throwing class cast exception.

Anyhelp would be appreciated.

Thanks, Priya.R


Java is strongly typed language. You can not pass a string to integer expecting method. You should convert string to integer, you can use Integer.parseInt() ..


If all inputs are Strings in the XML file, then there really is no difference between an XML file and a normal text file, is there?

The main problem is the representation of data types: you are not using XML as it's meant to be. XML files should represent the particular data type an input has. For example, a person's age should be represented as an int. You lose type semantics when you encode everything as a String.

As for actual code, use the XMLEncoder and XMLDecoder java classes located here and here, respectively.

Basically, you'll do something like:

XMLEncoder encoder = new XMLEncoder();
XMLDecoder decoder = new XMLDecoder();

Encoding (aka: Storing the data to the XML File) - Write the first input as an integer type (encoder.writeInt(someIntValue)) - Write the second input as a String: encoder.writeString(someStrValue) - etc

When decoding, you decode an integer first, then a String, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜