Created
December 12, 2021 17:16
-
-
Save orbyfied/ca0f9b82828bda478c7f7b2346b78852 to your computer and use it in GitHub Desktop.
Simple tuple class.
This file contains 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
/** | |
* Simple tuple class. | |
* @author orbyfied | |
*/ | |
public class Tuple { | |
/** | |
* Marks a field in a layout class as | |
* a unpackable field. | |
*/ | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target (ElementType.FIELD) | |
public @interface Packed { } | |
////////////////////////////////////////// | |
public static Tuple of(Object... o) { | |
return new Tuple(o); | |
} | |
////////////////////////////////////////// | |
/** | |
* The internal array storing the objects. | |
*/ | |
Object[] arr; | |
/* Constructors. */ | |
public Tuple(int s) { this.arr = new Object[s]; } | |
public Tuple(Object... objs) { this.arr = objs; } | |
public Tuple(int s, Object... objs) { | |
this(s); | |
System.arraycopy(objs, 0, arr, 0, objs.length); | |
} | |
/** | |
* Returns the internal array. | |
* @return The array. | |
*/ | |
public Object[] toArray() { | |
return arr; | |
} | |
/** | |
* Returns the internal array as a specific type. | |
* @return The array. | |
*/ | |
public <T> T[] toArray(Class<T> tClass) { | |
return (T[]) arr; | |
} | |
/** | |
* Returns the object at position i. | |
* @param i The index. | |
* @return The object. | |
*/ | |
public Object get(int i) { | |
return arr[i]; | |
} | |
/** | |
* Returns the object at position i with type T. | |
* @param i The index. | |
* @return The object. | |
*/ | |
public <T> T get(int i, Class<T> tClass) { | |
return (T) arr[i]; | |
} | |
/** | |
* Unpacks this tuple into a layout instance. Only | |
* puts values in fields marked with <code>@Tuple.Packed</code> | |
* and are empty. | |
* @param layout The layout instance. | |
* @param <T> The layout type. | |
* @return Gives back the layout instance. | |
*/ | |
public <T> T unpack(T layout) { | |
try { | |
Class<T> lc = (Class<T>) layout.getClass(); | |
int i = 0; | |
int l = arr.length; | |
for (Field f : lc.getDeclaredFields()) { | |
if (i == l) break; | |
if (!f.isAnnotationPresent(Packed.class)) continue; | |
if (f.get(layout) != null) continue; | |
f.setAccessible(true); | |
f.set(layout, arr[i]); | |
i++; | |
} | |
return layout; | |
} catch (Exception e) { e.printStackTrace(); return null; } | |
} | |
/** | |
* Unpacks the tuple into a new instance of | |
* class layout. Returns the new instance. | |
* @see Tuple#unpack(Object) | |
*/ | |
public <T> T unpack(Class<T> layout) { | |
try { | |
T l = layout.newInstance(); | |
return unpack(l); | |
} catch (Exception e) { e.printStackTrace(); return null; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment