0

Hi guys,
I am writing a method which given an instance of a class and a type (as a string), it will return an instance of the named type constructed from the instance if possible, null otherwise.
So say,

class A{
      A(B b) {
        ..
      }
      ..
}
class B {
      B(C c) {
        //
      }
      // …
}

class C {
      // ..
}

so method, conversion(new C(), "A"), should return A as conversion from C->A exists. Any ideas?

Edited by Nick Evan: Fixed formatting

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by javaAddict
0

There is no "conversion" involved. It is a simple cast, and after the return the instance will still be the same type it was before. And, it's not possible to "dynamically" change the return type of a method anyway, so the entire is doomed to failure. Maybe if you would explain what it is you are actually trying to accomplish we could help you.

0

Well, method returns A as an instance if coversion is possible using Java's reflection. This is the question our teacher gave us to think about. So, I am guessing we may see it on the quiz or exam.

0
public static Object convesrion(Object obj, String s) {

}

If you search the API for reflect and look at the Class class, I think that you can find methods that:
Using a String create a Class instance of the given type.
Methods that check if something can be cast.

Also as String argument be careful to add the package as well: Class.forName("pack.A");

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.