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);
Answer from user2308814 on Stack Overflow
Top answer
1 of 4
2

Whats wrong with creating a constructor in the respected class? or using a parsing decorator/object?

I.E.

public final class MyCustomRecordFromDB implements CustomRecordInterface {
    private final DatabaseRecord innerDBRecord;
    public MyCustomRecordFromDB(DatabaseRecord dbRecord) {
        this.innerDBRecord = dbRecord;
    }

    public Something A()
    {
        return ... ;
    }

    public Something B()
    {
        return ... ;
    }
}

Where CustomRecordInterface is the interface that MyCustomRecord implements (i.e. MyCustomRecordFromDB should be able to be a substitute to MyCustomRecord) as you should always code to interfaces in OOP (in case you want to follow OOP).

it is really similar to adapter object pattern.

Note: I've assumed that your setA(...) and setB(...) are public methods that have getter such as A() and B() respectfully, you can omit that if this isn't the case.

2 of 4
2

Few things I would consider when using a class in another. Constructor or No constructor.

  1. Coupling: I would avoid tight dependency between classes when not required or can be avoided.
  2. Encapsulation: If you change something, maybe a field in one class, you would end up changing the other class as well. This is a side effect. Desirable?
  3. The conversion might be simple for now - but in case you want to add logic/validations later, is constructor the right place for that?
  4. Single Responsibility Principle: Let your POJO do what it is meant to do. Why have another reason for the POJO to change?
  5. Testing: No matter how trivial the code is, you might want to make sure you can unit test it. Testing static methods, as others have mentioned, is difficult.

Based on these, I think it is better for you to follow the standard adapter pattern, create an adapter interface, and have a separate class provide its implementation.

Your POJOs will be simple, logic moved out, the coupling is reduced, can be tested easily.

Further, for your use case, you can also try using some object mappers that are readily available. Can avoid a lot of boilerplate code.

Discussions

java - Convert or Cast a Simple Object to Object of another class - Stack Overflow
How can I convert this pObject to object of the following class More on stackoverflow.com
🌐 stackoverflow.com
July 26, 2019
java - Best place to convert one object to another object - Software Engineering Stack Exchange
If, however, you make C objects directly dependent on A and B and try to avoid a separate converter class, all code using C objects will still depend on A and B, which is probably something you want to avoid. Think about what this means when you want to place the code using C in a separate ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
May 31, 2017
java - Convert String into a Class Object - Stack Overflow
I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object. How to do that? Please help me with source code. More on stackoverflow.com
🌐 stackoverflow.com
Transforming an object into a subclass of that object
You can't. When an object is created, its type is set. Casting it changes how you refer to it, but not what it actually is. You might be able to get some of what you want by having a constructor that takes an instance of the superclass and copies the common fields over. Basically though, it sounds like you're heading in the wrong direction and you're going to be fighting Java instead of working with it. Either you're pushing too much logic into your object tree, or you're mixing your factory and business logic too intimately. More on reddit.com
🌐 r/java
17
3
February 1, 2014
🌐
GeeksforGeeks
geeksforgeeks.org › java › class-cast-method-in-java-with-examples
Class cast() method in Java with Examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // cast() method import java.util.*; class Main { private static int obj = 10; public static void main(String[] args) throws ClassNotFoundException { try { // returns the Class object for this class Class myClass ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-string-to-object
Java Program to Convert String to Object - GeeksforGeeks
July 23, 2025 - We can also convert the string to an object using the Class.forName() method. ... Parameter: This method accepts the parameter className which is the Class for which its instance is required.
🌐
Baeldung
baeldung.com › home › java › core java › object type casting in java
Object Type Casting in Java | Baeldung
May 11, 2024 - When we do casting, we change the ... the object itself. Casting from a subclass to a superclass is called upcasting. Typically, the upcasting is implicitly performed by the compiler. Upcasting is closely related to inheritance — another core concept in Java. It’s common to use reference variables to refer to a more specific type. And every time we do this, implicit upcasting takes place. To demonstrate upcasting, let’s define an Animal class...
🌐
CodeGym
codegym.cc › java blog › inheritance in java › java class cast() method
Java Class Cast() Method
October 11, 2023 - In Java, there are different options for casting. One of them is the cast() method of the java.lang.Class class. it is used to cast the specified object to an object of this class. The method returns an object after being cast as...
Find elsewhere
🌐
Level Up Lunch
leveluplunch.com › java › tutorials › 016-transform-object-class-into-another-type-java8
Transform object into another type with Java 8 | Level Up Lunch
November 24, 2014 - For instance, you may make a rest web service request, cross business unit native call or vendor request that returns a Location object which you need to map to the internal MyLocation class. In episode 2 we walked through transforming from one object to another with guava, in this episode we will examine how to transform an object into another type with java 8. ... Before we get started, there is two concepts to cover. First is a java.util.function.Function which accepts one argument and produces a result. The second is stream intermediate operation map which converts each element in a stream into another object via the supplied function.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › class_cast.htm
Java Class cast() Method
package com.tutorialspoint; class A { public static void show() { System.out.println("Class A show() function"); } } class B { public static void show() { System.out.println("Class B show() function"); } } public class ClassDemo { public static void main(String[] args) { ClassDemo cls = new ClassDemo(); Class c = cls.getClass(); System.out.println(c); Object obj = new A(); B b1 = new B(); b1.show(); // casts object Object a = A.class.cast(b1); System.out.println(obj.getClass()); System.out.println(b1.getClass()); System.out.println(a.getClass()); } } Let us compile and run the above program, t
Top answer
1 of 3
6

This seems like a perfectly good example of using Adapter Pattern

Basically, you would create one interface that would have one method:

public interface Adapter
{
   ClassC ConvertObject();
}

And then you would create two classes, implementing this interface, like this:

class AdapterClass : Adapter
{
   private ClassA adaptee;
   public AdapterClassA(ClassA pAdaptee)
   {
        adaptee = pAdaptee;
   }

   public ClassC ConvertObject()
   {
      //Code that converts ClassA to ClassC
   }
}

class AdapterClassB : Adapter
{
   private ClassB adaptee;
   public AdapterClassB(ClassB pAdaptee)
   {
        adaptee = pAdaptee;
   }

   public ClassC ConvertObject()
   {
      //Code that converts ClassB to ClassC
   }
}

This way, you are decoupling the logic of type conversion into different classes, leaving the same interface to the user class.

Now, one might raise an issue with unnecessarily creating an interface when nobody but ClassC will invoke the constructor of adapter classes. The interface is not there just because of who will invoke the constructor. For instance, it will be easier to write unit tests if you have something like this.

Next, you might want to decouple the classes completely, and move the invokation of the constructor to some factory class, where ClassC would just see the Adapter interface and then it would not depend on ClassA or ClassB in any way. Of course, this is flirting with the violation of KISS principle, but I would call it a judgment call.

Bottom line is: If you want to decouple ClassC from ClassA and ClassB, there must be something that binds adapter classes. It can be an abstract parent class, or a regular parent class or an interface. Considering that the parent entity carries no information, it is logical to use interface.

2 of 3
4

But now I'm not sure if that's a nice thing to do because I'm coupling two data transfer objects.

Yes, this looks like a code smell.

Would it be better to create an InvoiceConverter class or even something else?

Probably yes. If I got you right, you then will have a data flow like

     [class A or B object] -> [Converter] -> [C object] -> [code using C]

and Converter is the only place in your code which is directly dependent from the APIs A and B, whilst C objects as well as the code using C objects will not depend on A or B any more (which is probably your goal here, to decouple the different parts of your system).

If, however, you make C objects directly dependent on A and B and try to avoid a separate converter class, all code using C objects will still depend on A and B, which is probably something you want to avoid. Think about what this means when you want to place the code using C in a separate library (using a compiled language). In the second case, this library needs to be linked against the APIs of A and B, whilst in the first case the lib does not need a linkage against A or B.

Top answer
1 of 9
33

I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object.

Your question is ambiguous. It could mean at least two different things, one of which is ... well ... a serious misconception on your part.


If you did this:

SomeClass object = ...
String s = object.toString();

then the answer is that there is no simple way to turn s back into an instance of SomeClass. You couldn't do it even if the toString() method gave you one of those funky "SomeClass@xxxxxxxx" strings. (That string does not encode the state of the object, or even a reference to the object. The xxxxxxxx part is the object's identity hashcode. It is not unique, and cannot be magically turned back into a reference to the object.)

The only way you could turn the output of toString back into an object would be to:

  • code the SomeClass.toString() method so that included all relevant state for the object in the String it produced, and
  • code a constructor or factory method that explicitly parsed a String in the format produced by the toString() method.

This is probably a bad approach. Certainly, it is a lot of work to do this for non-trivial classes.


If you did something like this:

SomeClass object = ...
Class c = object.getClass();
String cn = c.toString();

then you could get the same Class object back (i.e. the one that is in c) as follows:

Class c2 = Class.forName(cn);

This gives you the Class but there is no magic way to reconstruct the original instance using it. (Obviously, the name of the class does not contain the state of the object.)


If you are looking for a way to serialize / deserialize an arbitrary object without going to the effort of coding the unparse / parse methods yourself, then you shouldn't be using toString() method at all. Here are some alternatives that you can use:

  • The Java Object Serialization APIs as described in the links in @Nishant's answer.
  • JSON serialization as described in @fatnjazzy's answer.
  • An XML serialization library like XStream.
  • An ORM mapping.

Each of these approaches has advantages and disadvantages ... which I won't go into here.

2 of 9
32

Much easier way of doing it: you will need com.google.gson.Gson for converting the object to json string for streaming

to convert object to json string for streaming use below code

Gson gson = new Gson();
String jsonString = gson.toJson(MyObject);

To convert back the json string to object use below code:

Gson gson = new Gson();
MyObject = gson.fromJson(decodedString , MyObjectClass.class);

Much easier way to convert object for streaming and read on the other side. Hope this helps. - Vishesh

🌐
Reddit
reddit.com › r/java › transforming an object into a subclass of that object
r/java on Reddit: Transforming an object into a subclass of that object
February 1, 2014 -

Hi. I'm not new to programming but somewhat new to Java. I wanted to do this:

public Vehicle getNewVehicle() {
       return new Vehicle();
}

Bus b = (Bus)getNewVehicle();

Java won't let me do that--so what would be the right pattern for this? What I want to be able to do is write one method to return a superclass object and then let the programmer convert it into a subclass of that object whenever they want, with as little fuss. I want to avoid this kind of thing:

public Vehicle getNewVehicle(VehicleType vt) {
       switch (vt)  {
            case: Bus
                return new Bus();
            case: Car
                return new Car();
            case: Truck
                return new Truck();
      }
}
🌐
Javaspring
javaspring.net › blog › class-to-java-conversion
Class to Java Conversion: A Comprehensive Guide | JavaSpring.net
July 11, 2025 - Java, being a popular object - oriented programming language, provides a robust environment for implementing classes. Understanding how to convert a class design into Java code is crucial for building scalable, maintainable, and efficient applications. This blog will delve into the key aspects ...
🌐
Javatpoint
javatpoint.com › java-cast-object-to-class
Java Cast Object to Class - Javatpoint
Java Cast Object to Class with java tutorial, features, history, variables, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Quora
quora.com › What-is-the-need-for-converting-a-class-into-an-object-in-programming
What is the need for converting a class into an object in programming? - Quora
Answer (1 of 4): Class is like a Full module which contain lots of different method and variable in case if you call the class without making object then it will load full class at a time and till no technology is able to handle class directly that’s why we make object of class by which we ...
🌐
Coderanch
coderanch.com › t › 611602 › java › covert-object-class-object-class
How should I covert one object class to another object class which has same structure (Java in General forum at Coderanch)
May 14, 2013 - application(WrapperClass obj){ abc.WrapperClass obj1=(Object)obj; } or application(WrapperClass obj){ abc. WrapperClass obj1 = new WrapperClass (); obj1.test = obj.test abc.obj1.test2 test2= new abc.Obj1.tes2(); test2. variable = obj.test2.variable ..... } Is there any better approach?
Top answer
1 of 8
5

What you really want to do here is use composition and not inheritance. Keep all your objects as type Student, and then temporarily assign the behaviour of a TutorRole as it is required to each instance of Student.

With this design your Student class will contain a property (member variable) of type TutorRole that you can add or remove at runtime. Adding an isTutor() method will allow you to detemine whether a Student is a Tutor at runtime in a clear and concise manner.

The TutorRole class will encapsulate the behaviour (i.e. methods) of being a Tutor.

/*
 * The TutorRole can be set at runtime
 */
public class Student {

    private String facultyId;

    private TutorRole tutorRole = null;

    public boolean isTutor() {
        return !(tutorRole == null);
    }

    public void doTutorStuff() {
        if(isTutor()) {
            tutorRole.doTutorStuff();
        }
        else {
            throw new NotTutorException();
        }
    }

    public void setTutorRole(TutorRole tutorRole) {
        this.tutorRole = tutorRole;
    }
}

/*
 * Ideally this class should implement a generic interface, but I'll keep this simple
 */
public class TutorRole {

    public void doTutorStuff() {
        // implementation here
    }
}

/*
 * Now let's use our classes...
 */
Student st = new Student(); // not a tutor
st.setTutorRole(new TutorRole()); // now a tutor
if(st.isTutor()) {
    st.doTutorStuff();
}
st.setTutorRole(null); // not a tutor anymore

An alternative approach is to have a Tutor class contain a reference to a Student object, but it depends on how you are going to be interacting with the Student and Tutor objects on which way around you want to code this.

2 of 8
4

I think, this screams containment and interface programming.

How about this:

interface IStudent
{
  String getName();
  int getStudentId();
}

interface IFacultyMember
{
  int getFacultyId( );
}

class Student
  implements IStudent
{
  String name;
  int id;

  public String getName( ) { return name; }
  public int getStudentId( ) { return id; }
}

class Tutor
  implements IStudent, IFacultyMember
{
  Student student;
  int facultyId;

  public Tutor ( Student student, int facultyId )
  {
    this.student = student;
    this.facultyId = facultyId;
  }

  public String getName( ) { return student.getName( ); }
  public int getStudentId( ) { return student.getStudentId( ); }
  public int getFacultyId( ) { return facultyId; };
}

This way, your Student remains a student, even if it moves to the Tutor position. When Tutor's term expires you just GC the tutor record.

Student's record, on the other hand will still be available in Central Services.