Domanda [Sfida] Copiare un array utilizzando sun.misc.Unsafe

Stato
Discussione chiusa ad ulteriori risposte.

Sharker

Utente Bronze
14 Novembre 2014
13
2
2
43
Sfida per gli utenti che masticano il java, copiate un array di oggetti sfruttando solo il backdoor di Sun(sun.misc.Unsafe) per accedere alla memoria.

Il metodo deve essere dinamico
Codice:
public static <T> void copyArray(T[] src, T[] dest); //o throws Exception[COLOR=#880000][FONT=monospace]
[/FONT][/COLOR]


Mia soluzione:
Codice:
  public static <T> void copyArray(T[] src, T[] dest) throws Exception{
      if(dest == null || src == null)
           throw new Exception();

      Field f = Unsafe.class.getDeclaredField("theUnsafe");
      f.setAccessible(true);
      Unsafe mem = (Unsafe) f.get(null);

      Object[][] arrays = new Object[][]{new Object[]{src}, new Object[]{dest}};
      long[] addrs = new long[2];

      long baseOffset = mem.arrayBaseOffset(Object[].class);
      for(int x=0; x<arrays.length; x++)
           addrs[x] = (~0L >>> 32) & mem.getInt(arrays[x], baseOffset);

      mem.copyMemory(addrs[0], addrs[1], baseOffset + mem.arrayIndexScale(src.getClass()) * src.length);
  }
 
Stato
Discussione chiusa ad ulteriori risposte.