Convert or Cast a Simple Object to Object of another class
I've an object pObject
Object 开发者_StackOverflow中文版pObject = someRpcCall();
I don't know the type of pObject
What i know is System.out.println(pObject.toString())
outputs
{partner_shipping_id=12, partner_order_id=11, user_id=1, partner_invoice_id=13, pricelist_id=1, fiscal_position=false, payment_term=false}
How can I convert this pObject to object of the following class
import android.os.Parcel;
import android.os.Parcelable;
public class Customer implements Parcelable {
private int id;
private String name = "";
public Customer() {
// TODO Auto-generated constructor stub
}
/**
* This will be used only by the MyCreator
*
* @param source
*/
public Customer(Parcel source) {
/*
* Reconstruct from the Parcel
*/
id = source.readInt();
name = source.readString();
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
@Override
public Customer createFromParcel(Parcel source) {
return new Customer(source);
}
@Override
public Customer[] newArray(int size) {
return new Customer[size];
// TODO Auto-generated method stub
}
};
}
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;
}
精彩评论