-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move from reflection to method handles in OFM
Signed-off-by: TheSilkMiner <thesilkminer@outlook.com>
- Loading branch information
1 parent
55ce6b9
commit af0af3a
Showing
1 changed file
with
20 additions
and
2 deletions.
There are no files selected for viewing
22 changes: 20 additions & 2 deletions
22
Common/src/main/java/com/blamejared/contenttweaker/core/api/object/ObjectFactoryMapping.java
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
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); | ||
} | ||
} | ||
} |