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?

Dani AI

Generated

A concise way to think about this exam question: you cannot change an object's runtime class (as pointed out). What you can do is build a new instance of the requested type by discovering and invoking constructors or static factory methods that can be satisfied from the original object — possibly by doing that repeatedly (C -> B -> A in your example).

Algorithm sketch (practical and safe):

  • Load the target Class object and immediately return the source if it already satisfies the target.
  • Search for single-argument static factory methods on the target that return the target type; try to satisfy the factory's parameter from the source (recursively).
  • Search for constructors (prefer zero-arg and single-arg); for a single-arg constructor, try to build the constructor parameter from the source recursively.
  • Maintain a visited set plus a recursion depth limit to avoid infinite loops and exponential work. Cache successful conversions keyed by (sourceClass, targetClass) for speed.
  • Prefer public APIs; only use setAccessible(true) where acceptable and allowed.

Minimal implementation idea (illustrative):

// high-level idea: recursive search with visited set and depth limit
public static Object convert(Object src, String targetName) throws Exception {
    return convertTo(src, Class.forName(targetName), new HashSet<>(), 8);
}
private static Object convertTo(Object src, Class<?> target,
                                Set<Class<?>> busy, int depth) throws Exception {
    if (src == null || depth <= 0) return null;
    if (target.isInstance(src)) return src;
    if (!busy.add(target)) return null;
    // try static factories (single-arg), then constructors (zero- or single-arg)
    // on success return new instance; otherwise return null
    return null;
}

Cautions: you need fully-qualified names, handle primitives/autoboxing, watch security managers and access checks, and decide how to treat ambiguous matches or multi-parameter constructors. For reflection details see the Javadoc for Class and Constructor:

This approach follows the hints from about using reflection and implements 's correctness constraint (you build a new object rather than change the old one).

Recommended Answers

All 4 Replies

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.

Anyone?

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.