priya
priya

Reputation: 950

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

Upvotes: 0

Views: 827

Answers (2)

user402642
user402642

Reputation:

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.

Upvotes: 0

Gursel Koca
Gursel Koca

Reputation: 21280

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() ..

Upvotes: 4

Related Questions