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.
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.
The java. lang. Class. cast() method casts an object to the class or interface represented by this Class object.
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 MyClass
is 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With