[英]Convert or Cast a Simple Object to Object of another class
我有一個對象pObject
Object pObject = someRpcCall();
我不知道pObject
的類型
我所知道的是System.out.println(pObject.toString())
輸出
{partner_shipping_id=12, partner_order_id=11, user_id=1, partner_invoice_id=13, pricelist_id=1, fiscal_position=false, payment_term=false}
如何將此pObject轉換為以下類的對象
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
}
};
}
是什么輸出System.out.println(pObject.getClass().getName());
如果它是同一個Customer
類,那么你可以像這樣拋出對象
Customer cust = (Customer) pObject;
提供了上述問題的答案,但我有一個通用的解決方案,我希望與大家分享。
例如:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.