0

i have class type saved in string like this:

String cls = "Test";

Here is some code i tried:

String cls = "Test";

Object obj = new Test();

Test test = (Class.forName(cls)) obj;

But it ends with compilation error:

Main.java:21: error: ';' expected
        Test test = (Class.forName(cls)) obj;

How can I use this string for type conversion?

PS: Presume I don't know what type obj is, I only have String cls.

Zlopez
  • 660
  • 1
  • 5
  • 11
  • Distinguish the Class Test as an object (or an expression producing it) and the string `Test` as a sequence of 4 letters written in a Java program. There are worlds between these two. – laune Mar 18 '15 at 11:51
  • possible duplicate of [Java Class.cast() vs. cast operator](http://stackoverflow.com/questions/1555326/java-class-cast-vs-cast-operator) – Robert Moskal Mar 18 '15 at 11:54
  • I know, but how can i convert string in class, is there any option with full name of class in string like `com.package.Test` ? – Zlopez Mar 18 '15 at 11:56
  • You declare test to be of type 'Test' on the left hand side. So at this point in your program you know that you want to cast to the Test type. I think this is what is confusing people. You want the cast to be dynamically set using a string but at compile time you already know what type you are expecting. – darrenmc Mar 18 '15 at 12:13
  • @darrenmc Maybe i used the wrong example, but this is exactly what i want. Dynamically cast object by using a string with class name. – Zlopez Mar 18 '15 at 12:16
  • @Zlopez What is your use case for this behavior? At some point in your program you will want to know what the concrete type is so you can call methods on it etc. At this point you can cast it. Otherwise you can leave it as an object and use reflection to interrogate and interact with your instantiated object. – darrenmc Mar 18 '15 at 12:20
  • I want to use it to determine type of deserialized objects from array of strings with class names. – Zlopez Mar 18 '15 at 12:24

5 Answers5

2

If you want to instantiate a class for which you have the name, you were already on the right track:

// Remember that this class name tells us, it's in the default package, 
// otherwise you would have to use the fully qualified name, for example
// com.mydomain.Test

String className = "Test";

// First we need to get the correct class object

Class<?> clz = Class.forName(className);

// And from this class object, we can create a new instance, in other
// words, a "Test" object:

Test test = (Test)clz.newInstance();

Of course, there are some exceptions that have to be caught (or declared), etc. But I think you get the idea. If you do not want to call the default constructor (the one with no arguments, in other words the equivalent of new Test() ) of your "Test" class, you would have to search the right constructors via the appropriate methods of the Class object (getDeclaredConstructor, etc.etc. - see the API doc for that).

Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
  • This is good answer, but lets say I have a Object, but don't know what class it is and we have this class name saved in string. How can I convert the string to Class and use it for conversion. – Zlopez Mar 18 '15 at 12:00
  • I am not sure if what you are asking for, sorry... Could you clarify your problem, tell us, what you want to accomplish in the end? – Florian Schaetz Mar 18 '15 at 12:05
1

You can use the cast method on the Class you created from the String:

String className = "Test";
Class<?> clz = Class.forName(className);
clz.cast(objectToBecasted);
Erwin de Gier
  • 632
  • 7
  • 12
  • 1
    @Zlopez , just go and check this **[Demo](http://ideone.com/4G07Dr)** , you will get compilation error as you again need to explicit cast it !! – Neeraj Jain Mar 18 '15 at 13:00
  • Thx, i didn't try it. It looks like there is no option without knowing the class type or using `instanceof` against possible class types and then cast? – Zlopez Mar 18 '15 at 13:34
  • What are you trying to achieve? Casting because you want to use a different compile time type implies that you know the type. The only other option I see is with generics, when you get the type passed in a method as an argument. See also [this question](http://stackoverflow.com/questions/7900410/why-would-i-use-java-lang-class-cast) – Erwin de Gier Mar 18 '15 at 14:21
0

java.lang.class.Class c=Class.forName("ClassNameToBeLoadedDynamically") is not required as

A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime).

You can directly use

Test test = (Test) obj;
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

Ok,

Try this:

Test test = (Test) Class.forName(cls).cast(obj);
Johnny
  • 1,063
  • 1
  • 11
  • 23
  • But it presumes I know what Class is obj is, but presume I don't and have this Class name saved only in string. – Zlopez Mar 18 '15 at 12:03
  • Sorry can't understand, could you rephrase? – Johnny Mar 18 '15 at 12:07
  • I don't know if obj is class type `Test`, but I have class name saved in `String cls` – Zlopez Mar 18 '15 at 12:10
  • 2
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment). – Alberto Zaccagni Mar 18 '15 at 14:12
  • @AlbertoZaccagni what? Was it addressed to me? – Johnny Mar 19 '15 at 09:12
  • It is good practice to explain why your proposed solution solves OP's problem :) – Alberto Zaccagni Mar 19 '15 at 09:14
0
    String cls = "Test";

    Test t = new Test();

    OtherTest ot = new OtherTest();

    Class<?> c = Class.forName(cls);

    if(t.getClass() == c) {
        System.out.println("Hooray!");
    }

    if(ot.getClass() == c) {
        System.out.println("Mmmmh");
    }

It prints out "Hooray"

Is this what you want?

Johnny
  • 1,063
  • 1
  • 11
  • 23
  • No He does not want to Compare the Classes , he actually want to cast it down !!! – Neeraj Jain Mar 18 '15 at 13:01
  • Yes but before casting the unknown object you should check whether the class is a match or you are going to incur a ClassCastException... this was an addition to a previous answer I made. I should have bundled them together, I know. – Johnny Mar 19 '15 at 09:08
  • @Johny , Then you should probably edit your previous answer and Add this there only . No Point in giving multiple answers – Neeraj Jain Mar 19 '15 at 10:01