Space Rocker
Space Rocker

Reputation: 787

how to relate string to object instances in java

I have a code block where i deserialize incoming data and then i have to cast this into some known class object, so for that reason i do something like this:

   if (object instanceof MyClass) {
         Myclass data = (MyClass)object;  
   }

it works fine, however now i have a situation where there could be different type of calsses. So is there a way to do the comparison based on "String":

   if (object instanceof "String") {
         String data = (String)object;  
   }

the problem is in this case, the user will specify the class object name, so how can i do that?
Should i force user to initiate a dummy object and then pass to my method or is there a way to initialize null object with String, any ideas?

Upvotes: 2

Views: 207

Answers (4)

Sudhakar
Sudhakar

Reputation: 4873

you can use Class#forName() and Class#isInstance(Object). to accomplish this

Heres a sample code

FileDemo dd = new FileDemo();
Class object = Class.forName("com.FileDemo");

if(object.isInstance(object)){
    //do your conversion
}

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359816

It's smelly, ugly, and I don't like it, but you can use Class#forName() and Class#isInstance(Object).

if (Class.forName("java.lang.String").isInstance(object)) {
     String data = (String)object;  
}

You're still going to have problems with the cast, though. Class#cast() only gets you compile-time type safety when you've got a Class<T> – but you can only get a Class<?> from Class#forName().

Upvotes: 5

Vyassa Baratham
Vyassa Baratham

Reputation: 1467

See the "forname" method here: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

Upvotes: 0

Woot4Moo
Woot4Moo

Reputation: 24316

You can always do this:

if(object instanceof MyClass)  
{
             Myclass data = (MyClass)object;  
} else  
{  
       String data = object.toString();
}  

By default every Object in java has a toString function that can be invoked. There is no need to cast to a String

Upvotes: 1

Related Questions