0

I'm trying to do this:

Field field = classeDoObjetoDaColecao.getDeclaredField(caminho[0]);

//Here I get the setMethod, based on the attribute (via field)
Method metodoSet = classeDoObjetoDaColecao.getMethod(partesLista[0], field.getType());


metodoSet.invoke(objetoNovo,field.getType().cast(value));   

Where value is a Stringand field` is a primitive int.

This generates an exception that String can't be cast to int.

2
  • 3
    Casting doesn't change an object. Commented Aug 1, 2014 at 15:38
  • You won't use reflection for the conversion. You'll use Integer.parseInt(..) after figuring out that it's a String which you want to convert to an int. Commented Aug 1, 2014 at 15:38

2 Answers 2

2

Simple Answer. You cant cast String to int.

try to use

    Integer.parseInt(String);

An Cast dont convert an Object. It just specify it.

For example you haven a Superclass with 2 Subclasses.

The you can cast from Super to Subclass.

Sign up to request clarification or add additional context in comments.

Comments

0

There's no dynamic way to do this. You need to establish that you have a field of type int or Integer and a value of type String which you want to convert.

Once you have that, you can use Integer.parseInt(..) to do the conversion.

If you then want to add other conversion pairs, you need to do the same thing. Find the source and target type and do the appropriate conversion based on those types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.