Created
July 31, 2012 19:28
-
-
Save sampsyo/3219778 to your computer and use it in GitHub Desktop.
Java object cloning for Jikes RVM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Array; | |
import org.vmmagic.unboxed.Address; | |
import org.vmmagic.unboxed.ObjectReference; | |
import org.vmmagic.unboxed.Offset; | |
import org.mmtk.vm.VM; | |
import org.vmmagic.pragma.Uninterruptible; | |
import org.jikesrvm.classloader.RVMType; | |
import org.jikesrvm.runtime.RuntimeEntrypoints; | |
import org.jikesrvm.runtime.Memory; | |
public class CopyMachine { | |
// Copy the contents of one object into another. Both objects should have | |
// the same type (and certainly must have the same size), although this is | |
// not checked. | |
@Uninterruptible | |
public static void copy(Object src, Object dest) { | |
ObjectReference srcRef = ObjectReference.fromObject(src); | |
int size = VM.objectModel.getCurrentSize(srcRef); | |
Address srcAddr = VM.objectModel.objectStartRef(srcRef); | |
Address destAddr = VM.objectModel.objectStartRef( | |
ObjectReference.fromObject(dest) | |
); | |
Memory.memcopy(destAddr, srcAddr, size); | |
} | |
// Create a new object that is a (shallow) copy of a different object. | |
@SuppressWarnings("unchecked") | |
public static <T> T clone(T obj) { | |
RVMType rtype = java.lang.JikesRVMSupport.getTypeForClass( | |
obj.getClass() | |
); | |
if (rtype.isClassType()) { | |
Object out = RuntimeEntrypoints.resolvedNewScalar(rtype.asClass()); | |
copy(obj, out); | |
return (T)out; | |
} else if (rtype.isArrayType()) { | |
Object out = RuntimeEntrypoints.resolvedNewArray( | |
Array.getLength(obj), | |
rtype.asArray() | |
); | |
copy(obj, out); | |
return (T)out; | |
} else { | |
assert false; | |
return null; | |
} | |
} | |
public static void main(String[] args) { | |
String foo = "foo"; | |
String bar = clone(foo); | |
System.out.println(bar); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment