gene b.
gene b.

Reputation: 11984

Dynamic Casting in Java with Variable Class Name

If I have a variable method param which takes a Class to cast to, how do I dynamically implement the cast? And how would I declare the variable result?

Obviously this is wrong,

public void test(Class destinationClass)
{
   (destinationClass)result = (destinationClass)getObject();
}

Note: getObject() returns an object castable to Destination Class. A Destination Class object is a child of getObject().

Upvotes: 0

Views: 4734

Answers (3)

dsp_user
dsp_user

Reputation: 2119

You can use reflection, if you want to create an object dynamically (this is useful when the exact types are not known at compile time)

public <T> T getObj(Class<T> target){
T obj= target.getConstructor().newInstance();
return obj;
}

This assumes that the target class has a no-args constructor, but you see the pattern.

Upvotes: 0

WalterM
WalterM

Reputation: 2706

This is a case for generic methods.

class MyObject {
    private Object obj;

    public void setObject(Object o) {
        this.obj = o;
    }

    public <T>T getObject() { //notice return type
        return (T) obj;       //and cast
    }
}

Then just use this code to run it and see what it does.

MyObject o = new MyObject();

o.setObject("Hello World!");
String s = o.getObject();
System.out.println(s);

o.setObject(1000);
Integer i = o.getObject();
System.out.println(i);

s = o.getObject(); //will throw exception because the object is an integer

//can also use this to specify return type
o.<Integer>getObject();

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198033

public <T> void test(Class<T> destinationClass) {
  T result = destinationClass.cast(getObject());
  ...
}

Upvotes: 4

Related Questions