0

I wonder If It is possible to cast dynamically an object in Java.

For example, something like this:

return (object1.getClass().getSimpleName()) Object2;
Mureinik
  • 297,002
  • 52
  • 306
  • 350
csadan
  • 291
  • 1
  • 3
  • 13
  • What do you want to do? Why? – M. le Rutte Oct 06 '17 at 10:09
  • @M.leRutte The context is more complex, I am working with dynamic proxies and casting dynamically an object is crucial for such a goal. Otherwise, I have to do it manually. – csadan Oct 06 '17 at 10:12
  • Without more context it is impossible to answer, but in general the answer of @mureinik below is how you can ask a class object to cast an object. But not from incompatible types. – M. le Rutte Oct 06 '17 at 10:13
  • what is the point doing it inside a return statement? It will be reduced to the return type of the method, so you could just put in a cast with the same type as the method return type, e.g. `return (Foo) Object2;` – Absurd-Mind Oct 06 '17 at 10:27

1 Answers1

2

You can use Class.cast:

return object1.getClass().cast(Object2);
Mureinik
  • 297,002
  • 52
  • 306
  • 350