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 OverflowI 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).
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.
Few things I would consider when using a class in another. Constructor or No constructor.
- Coupling: I would avoid tight dependency between classes when not required or can be avoided.
- 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?
- The conversion might be simple for now - but in case you want to add logic/validations later, is constructor the right place for that?
- Single Responsibility Principle: Let your POJO do what it is meant to do. Why have another reason for the POJO to change?
- 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.
java - Convert or Cast a Simple Object to Object of another class - Stack Overflow
java - Best place to convert one object to another object - Software Engineering Stack Exchange
java - Convert String into a Class Object - Stack Overflow
Transforming an object into a subclass of that object
If PerformanceInvokeService has an accessible default constructor, you can create a new instance using:
Object instance = c.newInstance();
You can then pass that to the method invocation:
Object ret = m.invoke(instance, new Object[] { "some string", new Date() });
If there is no accessible default constructor, then you'll have to find a constructor that you can use by using reflection.
Class has a newInstance() method that you can call to create an instance of the class using its default constructor. Or, you can call getConstructor() or getConstructors() to find a constructor that takes the right kind of arguments, and then call newInstance() on the Constructor object, passing the construction arguments.
Whats the output of System.out.println(pObject.getClass().getName());
If its the same Customer class, then you could cast the object like this
Customer cust = (Customer) pObject;
The answer to the above problem is provided, but I have a generic solution which I want to share all of you.
- First, fetch the class name using Object object(provided)
- Using Enum know the Class name
- Create a reference object of the known class
- Initialize your Object class object
e.g:
package com.currentobject;
import com.currentobject.model.A;
import com.currentobject.model.B;
import com.currentobject.model.C;
Class CurrentObject{
public void objectProvider(Object object){
String className = object.getClass().getCanonicalName();
ModelclassName modelclass = ModelclassName.getOperationalName(className);
switch (modelclass) {
case A:
A a = (A) object;
break;
case B:
B b = (B) object;
break;
case C:
C c = (C) object;
break;
}
}
}
enum ModelclassName {
A("com.currentobject.model.A"),
B("com.currentobject.model.B"),
C("com.currentobject.model.C");
private ModelclassName(String name) {
this.name = name;
}
public static ModelclassName getOperationalName(final String operationName) {
for(ModelclassName oprname :ModelclassName.values()) {
if(oprname.name.equalsIgnoreCase(operationName)){
return oprname ;
}
}
return null;
}
String name;
}
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.
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.
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.
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
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();
}
}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.
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.