आप प्रतिबिंब इस्तेमाल करने की कोशिश कर सकते हैं:
public abstract class AClonable implements Cloneable{
private String val;
public AClonable(){
}
public AClonable(String s){
val=s;
}
public String toString(){
return val;
}
@Override
public AClonable clone(){
try {
System.out.println(getClass().getCanonicalName());
AClonable b= getClass().getDeclaredConstructor(String.class).newInstance(val);
return b;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
} विधि क्लोन() में
आप getClass फोन()। चूंकि ACloneble ist सार है, वहाँ कॉल कंक्रीट कक्षा में जायेंगे।
public class ClonebaleOne extends AClonable{
public ClonebaleOne(){
super();
}
public ClonebaleOne(String s) {
super(s);
// TODO Auto-generated constructor stub
}
}
और
public class ClonebaleTwo extends AClonable{
public ClonebaleTwo(){
super();
}
public ClonebaleTwo(String s) {
super(s);
// TODO Auto-generated constructor stub
}
}
और अंत में
public static void main(String[] args){
AClonable one = new ClonebaleOne("One");
AClonable tow= new ClonebaleTwo("Two");
AClonable clone = one.clone();
System.out.println(clone.toString());
clone = tow.clone();
System.out.println(clone.toString());
}
आउटपुट:
)
[संपादित करें] पूरा नहीं करने के लिए;
ClonebaleOne
One
ClonebaleTwo
Two
लेकिन यह अधिक एक समाधान
[संपादित करें] मेरे दो क्लोन की तुलना में तेजी थे की तुलना में एक हैक है। क्लोन() का एक अन्य इम्प्लांटेशन
@Override
public AClonable clone(){
try {
ByteArrayOutputStream outByte = new ByteArrayOutputStream();
ObjectOutputStream outObj = new ObjectOutputStream(outByte);
ByteArrayInputStream inByte;
ObjectInputStream inObject;
outObj.writeObject(this);
outObj.close();
byte[] buffer = outByte.toByteArray();
inByte = new ByteArrayInputStream(buffer);
inObject = new ObjectInputStream(inByte);
@SuppressWarnings("unchecked")
Object deepcopy = inObject.readObject();
inObject.close();
return (AClonable) deepcopy;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
जब आपका सार वर्ग Serialazable लागू करता है। वहां आप डिस्क पर अपना ऑब्जेक्ट लिखते हैं और डिस्क से मूल्य के साथ एक प्रति बनाते हैं।
स्रोत
2013-08-09 12:27:43
प्रतिबिंब का उपयोग करें? – johnchen902