dimanche 28 octobre 2018

Java class extend another class using reflection (bukkit)

I am trying to make an Anvil GUI for my bukkit plugin. I am trying to make my code cross-version compatible. However the class FakeAnvil need to extend the class ContainerAnvil, and this class is in the NMS package... is there any way that I can extend the class with reflection?

Here's my code:

package me.raymondliu1;

import java.lang.reflect.Constructor;
import org.bukkit.Bukkit;
//These five import is making the plugin not cross-version compatible
import net.minecraft.server.v1_8_R1.BlockPosition;
import net.minecraft.server.v1_8_R1.ContainerAnvil;
import net.minecraft.server.v1_8_R1.EntityHuman;
import net.minecraft.server.v1_8_R1.PlayerInventory;
import net.minecraft.server.v1_8_R1.World;


//problem 1
public final class FakeAnvil extends ContainerAnvil {
static Class<?> entityHumanClass;
static Class<?> BlockPositionClass;
static Class<?> ContainerAnvilClass;
static Constructor<?> bpc;
static Constructor<?> cac;
static{
    try {
        entityHumanClass = getNMSClass("EntityHuman");
        BlockPositionClass = getNMSClass("BlockPosition");
        ContainerAnvilClass = getNMSClass("ContainerAnvil");
        cac = ContainerAnvilClass.getConstructor(PlayerInventory.class,World.class,BlockPositionClass,entityHumanClass);
        bpc = BlockPositionClass.getConstructor(int.class,int.class,int.class);

    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
        e.printStackTrace();
    }
}
private static Class<?> getNMSClass(String nmsClassString) throws ClassNotFoundException {
    String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3] + ".";
    String name = "net.minecraft.server." + version + nmsClassString;
    Class<?> nmsClass = Class.forName(name);
    return nmsClass;
}
public FakeAnvil(Object entityHuman) throws Exception {
    //Problem 2
    super((PlayerInventory)entityHumanClass.getField("inventory").get(entityHuman), (World)entityHumanClass.getField("inventory").get("world"), (BlockPosition)bpc.newInstance(0,0,0), (EntityHuman)entityHuman);

}
@Override
public boolean a(EntityHuman entityHuman) {    
    return true;
}
}





Aucun commentaire:

Enregistrer un commentaire