All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.jorel.commandapi.SafeVarHandle Maven / Gradle / Ivy

The newest version!
package dev.jorel.commandapi;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

/**
 * A wrapper around VarHandle with better type safety using generics and a
 * toggleable underlying implementation depending on whether we're using mojang
 * mappings or non-mojang mappings
 *
 * @param 
 * @param 
 */
public class SafeVarHandle {

	public static boolean USING_MOJANG_MAPPINGS = MojangMappedVersionHandler.isMojangMapped();

	private VarHandle handle;

	private SafeVarHandle(VarHandle handle) {
		this.handle = handle;
	}

	private static  SafeVarHandle of(Class classType, String fieldName, String mojangMappedFieldName, Class fieldType)
		throws ReflectiveOperationException {
		return new SafeVarHandle<>(
			MethodHandles.privateLookupIn(classType, MethodHandles.lookup()).findVarHandle(classType, USING_MOJANG_MAPPINGS ? mojangMappedFieldName : fieldName, fieldType));
	}

	public static  SafeVarHandle ofOrNull(Class classType, String fieldName, String mojangMappedFieldName, Class fieldType) {
		try {
			return of(classType, fieldName, mojangMappedFieldName, fieldType);
		} catch (ReflectiveOperationException e) {
			e.printStackTrace();
			return null;
		}
	}

	public FieldType get(Type instance) {
		return (FieldType) handle.get(instance);
	}

	public FieldType getStatic() {
		return (FieldType) handle.get(null);
	}

	public void set(Type instance, FieldType param) {
		handle.set(instance, param);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy