Skip to content

Instantly share code, notes, and snippets.

@aikar
Created December 15, 2016 01:49
Show Gist options
  • Save aikar/e2b6cc06508a98417b71845a29429e3a to your computer and use it in GitHub Desktop.
Save aikar/e2b6cc06508a98417b71845a29429e3a to your computer and use it in GitHub Desktop.
/*
* Copyright (c) 2016. Starlis LLC / dba Empire Minecraft
*
* This source code is proprietary software and must not be redistributed without Starlis LLC's approval
*
*/
package com.empireminecraft.util.java;
import com.google.common.base.Supplier;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import java.lang.reflect.Field;
import java.util.Map;
@SuppressWarnings({"Guava", "Convert2MethodRef"})
public final class CustomMapTable {
private static Field BACKING_MAP;
private static Field FACTORY;
static {
try {
Class STANDARD_TABLE = Class.forName("com.google.common.collect.StandardTable");
BACKING_MAP = STANDARD_TABLE.getDeclaredField("backingMap");
FACTORY = STANDARD_TABLE.getDeclaredField("factory");
BACKING_MAP.setAccessible(true);
FACTORY.setAccessible(true);
} catch (ClassNotFoundException | NoSuchFieldException e) {
e.printStackTrace();
}
}
private CustomMapTable() {
}
public static <R, C, V> Table<R, C, V> create(Supplier<Map<R, Map<C, V>>> rowMap, Supplier<? extends Map<C, V>> columnMap) {
if (BACKING_MAP == null || FACTORY == null) {
throw new IllegalStateException("Could not replace backing map or factory");
}
final HashBasedTable<R, C, V> backing = HashBasedTable.create();
try {
BACKING_MAP.set(backing, rowMap.get());
FACTORY.set(backing, columnMap);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not replace backing map or factory", e);
}
return backing;
}
// Don't know why but constructor references won't compile, must be lamda
public static <V> Table<Long, Long, V> createLongLong() {
return create(() -> new Long2ObjectOpenHashMap<>(), () -> new Long2ObjectOpenHashMap<>());
}
public static <C, V> Table<Long, C, V> createLong(Supplier<? extends Map<C, V>> columnMap) {
return create(() -> new Long2ObjectOpenHashMap<>(), columnMap);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment