Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package gof.prototype;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.util.ArrayList;
- import java.util.List;
- /**
- *
- * @author Wojciech
- */
- public interface IPrototype extends Serializable{
- default public <T> T deepClone() {
- T clone = null;
- try {
- ByteArrayOutputStream baOUT = new ByteArrayOutputStream();
- ObjectOutputStream oOUT = new ObjectOutputStream(baOUT);
- oOUT.writeObject(this);
- ByteArrayInputStream baIN = new ByteArrayInputStream(baOUT.toByteArray());
- ObjectInputStream oIN = new ObjectInputStream(baIN);
- clone = (T) oIN.readObject();
- } catch (IOException | ClassNotFoundException e) {//Java 7 required
- e.printStackTrace();
- }
- return clone;
- }
- default public <T> T shallowClone() {
- T clone = null;
- try {
- // Get object's constructor
- Constructor[] constructors = this.getClass().getDeclaredConstructors();
- // Check if constructor exists
- if (constructors.length == 0) {
- throw new InstantiationException("No constructor was found.");
- }
- // Prepare null/zero constructor param list
- List<Object> paramList = new ArrayList();
- // Get constructor param types
- Class[] paramTypes = constructors[0].getParameterTypes();
- // Fill in param list
- for (Class paramType : paramTypes) {
- if (paramType.isPrimitive()) {
- paramList.add(0);
- } else {
- paramList.add(null);
- }
- }
- // Create 'empty' instance
- clone = (T) constructors[0].newInstance(paramList.toArray());
- // Copy-paste all declared fields to new instance
- Field[] fields = this.getClass().getDeclaredFields();
- for (Field field : fields) {
- field.set(clone, field.get(this));
- }
- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
- }
- return clone;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement