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?

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.

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.

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");

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.