0

Possible Duplicate:
Cast via reflection and use of Class.cast()

I have a question related to java programming. I want to have the ability to choose the casting type through a string parameter passed to the function. As you see there is a main class which have to be casted to a sub type. These subtype should be specified by the user. How we can do that ?

public void casting(String subClassCast)
 {
      MainClass mainClass = (subClassCast) MainClassFactory.get();
 }
Community
  • 1
  • 1
Hatem Salem
  • 175
  • 2
  • 3
  • 12
  • Why would you want to do this? If you don't know at compile time what to cast to, then there's no reason to do a cast. – Jesper Dec 19 '12 at 09:00

2 Answers2

2

The cast as you write it does nothing.

The cast serves for assigning an object of a superclass to a subclass reference

Object obj = a.toString();
String str = (String) obj;  // The compiler can't check that at runtime obj will be
                            // a String, so the programmer "forces" the compiler to
                            // allow the assignation

needs a cast, but in

Object obj2 = (String) obj;

the cast does nothing (other than throwing a ClassCastException if obj is not a String).

SJuan76
  • 24,532
  • 6
  • 47
  • 87
0

You could do:

MainClass mainClass = Class.forName(subClassCast).cast(MainClassFactory.get());

But I'm not sure it is a good idea.

ante
  • 1,045
  • 10
  • 29