Skip to content

Commit

Permalink
Move from reflection to method handles in OFM
Browse files Browse the repository at this point in the history
Signed-off-by: TheSilkMiner <thesilkminer@outlook.com>
  • Loading branch information
TheSilkMiner committed Jun 20, 2022
1 parent 55ce6b9 commit af0af3a
Showing 1 changed file with 20 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,30 @@
package com.blamejared.contenttweaker.core.api.object;

import com.blamejared.crafttweaker.api.util.InstantiationUtil;
import com.blamejared.crafttweaker.api.CraftTweakerAPI;
import com.blamejared.crafttweaker.api.util.GenericUtil;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.WrongMethodTypeException;

@FunctionalInterface
public interface ObjectFactoryMapping<T, U extends ObjectFactory<T>> {
Class<U> type();

default U of() {
return InstantiationUtil.getOrCreateInstance(this.type());
try {
final MethodHandles.Lookup lookup = MethodHandles.publicLookup();
final MethodType constructorType = MethodType.methodType(void.class);
final MethodHandle constructor = lookup.findConstructor(this.type(), constructorType);
return GenericUtil.uncheck(constructor.invoke());
} catch (final WrongMethodTypeException | ClassCastException e) {
CraftTweakerAPI.LOGGER.error(() -> "Unable to construct class '" + this.type().getName() + "' due to an invocation error", e);
throw e;
} catch (final Throwable e) {
CraftTweakerAPI.LOGGER.error(() -> "Unable to construct class '" + this.type().getName() + "' due to a construction error", e);
if (e instanceof RuntimeException re) throw re;
throw new RuntimeException("%s: %s".formatted(e.getClass().getName(), e.getMessage()), e);
}
}
}

0 comments on commit af0af3a

Please sign in to comment.