Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically converting java object of Object class to a given class when class name is known

People also ask

How dynamically create an object in Java from a class name given as string format?

In order to dynamically create an object in Java from an inner class name, you should use the $ sign. For Example: String className = "MyTestClass"; String innerClassName = "MyInnerTestClass"; String fullPathOfTheClass = "full.

How can we convert one class object to another class in Java?

Gson for converting one class object to another. First convert class A's object to json String and then convert Json string to class B's object. Show activity on this post. Copy the property values of the given source bean into the **target bean.

How do you convert an object to a particular object in Java?

The java. lang. Class. cast() method casts an object to the class or interface represented by this Class object.

Can an object created from a class be given the same name as the class?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.


I think its pretty straight forward with reflection

MyClass mobj = MyClass.class.cast(obj);

and if class name is different

Object newObj = Class.forName(classname).cast(obj);

you don't, declare an interface that declares the methods you would like to call:

public interface MyInterface
{
  void doStuff();
}

public class MyClass implements MyInterface
{
  public void doStuff()
  {
    System.Console.Writeln("done!");
  }
}

then you use

MyInterface mobj = (myInterface)obj;
mobj.doStuff();

If MyClassis not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).


You don't have to convert the object to a MyClass object because it already is. What you really want to do is to cast it, but since the class name is not known at compile time, you can't do that, since you can't declare a variable of that class. My guess is that you want/need something like "duck typing", i.e. you don't know the class name but you know the method name at compile time. Interfaces, as proposed by Gregory, are your best bet to do that.


If you didnt know that mojb is of type MyClass, then how can you create that variable?

If MyClass is an interface type, or a super type, then there is no need to do a cast.


@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
    return (T) obj;
}