简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM