Смена ника в игре

Версия Minecraft
1.12.2
API
Forge
34
2
4
Добрый вечер, делаю мод для смены ника в игре(в главном меню) получаю ник так
Minecraft.getMinecraft().getSession().getUsername());
Подскажите какой функцией можно его изменить. Всё естественно для пиратского майна
 
Решение
Можно было исходник Session посмотреть для понимания аргументов конструктора.

На работоспособность не проверял.
Java:
class Scratch {

    public static void createNewSession(String username) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        Session session = new Session(username, uuid, "SESSION_ID", "mojang");

        try {
            setSession(session);
        } catch (ReflectiveOperationException e) {
            LogManager.getLogger().error("Failed to set new session", e);
        }
    }

    public static void setSession(Session session) throws ReflectiveOperationException {
        Field field = ReflectionHelper.findField(Minecraft.class, "field_71449_j", "session"); // SRG & MCP names...
34
2
4
Это элементарно
  1. Создать новый объект Session с нужным ником, токеном и др.
  2. Заменить им старый через рефлексию (поле Minecraft.session)
т.е я создаю сессию примерно так(хз насколько правильно):
Session session = new Session("MyNick", UUIDTypeAdapter.fromUUID(Minecraft.getMiecraft().getSession().getProfile().getId()), Minecraft.getMinecraft().getSession().getToken(), Minecraft.getMinecraft().getSession().getUsername());
Можешь немного пояснить про рефлексию, я не совсем понимаю как её применить
 
1,074
72
372
Можно было исходник Session посмотреть для понимания аргументов конструктора.

На работоспособность не проверял.
Java:
class Scratch {

    public static void createNewSession(String username) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        Session session = new Session(username, uuid, "SESSION_ID", "mojang");

        try {
            setSession(session);
        } catch (ReflectiveOperationException e) {
            LogManager.getLogger().error("Failed to set new session", e);
        }
    }

    public static void setSession(Session session) throws ReflectiveOperationException {
        Field field = ReflectionHelper.findField(Minecraft.class, "field_71449_j", "session"); // SRG & MCP names

        if(!field.isAccessible()) {
            field.setAccessible(true);
            removeFinalFlag(field);
        }

        field.set(Minecraft.getMinecraft(), session);
    }

    public static void removeFinalFlag(Field field) throws ReflectiveOperationException {
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    }
}
Используйте на свой страх и риск. Автор не несёт ответственности за причинённый ущерб. 😏
 
34
2
4
Можно было исходник Session посмотреть для понимания аргументов конструктора.

На работоспособность не проверял.

Краш, что-то с field_71449_j не так

Java:
---- Minecraft Crash Report ----
// Shall we play a game?

Time: 8/6/21 5:31 PM
Description: There was a severe problem during mod loading that has caused the game to fail

net.minecraftforge.fml.common.LoaderExceptionModCrash: Caught exception from Example Mod (examplemod)
Caused by: net.minecraftforge.fml.relauncher.ReflectionHelper$UnableToFindFieldException: java.lang.NoSuchFieldException: field_71449_j
    at net.minecraftforge.fml.relauncher.ReflectionHelper.findField(ReflectionHelper.java:166)
    at com.example.examplemod.ChangeNick.setSession(ChangeNick.java:25)
    at com.example.examplemod.ChangeNick.createNewSession(ChangeNick.java:18)
    at com.example.examplemod.ExampleMod.init(ExampleMod.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraftforge.fml.common.FMLModContainer.handleModStateEvent(FMLModContainer.java:639)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.google.common.eventbus.Subscriber.invokeSubscriberMethod(Subscriber.java:91)
    at com.google.common.eventbus.Subscriber$SynchronizedSubscriber.invokeSubscriberMethod(Subscriber.java:150)
    at com.google.common.eventbus.Subscriber$1.run(Subscriber.java:76)
    at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:399)
    at com.google.common.eventbus.Subscriber.dispatchEvent(Subscriber.java:71)
    at com.google.common.eventbus.Dispatcher$PerThreadQueuedDispatcher.dispatch(Dispatcher.java:116)
    at com.google.common.eventbus.EventBus.post(EventBus.java:217)
    at net.minecraftforge.fml.common.LoadController.sendEventToModContainer(LoadController.java:219)
    at net.minecraftforge.fml.common.LoadController.propogateStateMessage(LoadController.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.google.common.eventbus.Subscriber.invokeSubscriberMethod(Subscriber.java:91)
    at com.google.common.eventbus.Subscriber$SynchronizedSubscriber.invokeSubscriberMethod(Subscriber.java:150)
    at com.google.common.eventbus.Subscriber$1.run(Subscriber.java:76)
    at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:399)
    at com.google.common.eventbus.Subscriber.dispatchEvent(Subscriber.java:71)
    at com.google.common.eventbus.Dispatcher$PerThreadQueuedDispatcher.dispatch(Dispatcher.java:116)
    at com.google.common.eventbus.EventBus.post(EventBus.java:217)
    at net.minecraftforge.fml.common.LoadController.distributeStateMessage(LoadController.java:136)
    at net.minecraftforge.fml.common.Loader.initializeMods(Loader.java:749)
    at net.minecraftforge.fml.client.FMLClientHandler.finishMinecraftLoading(FMLClientHandler.java:336)
    at net.minecraft.client.Minecraft.init(Minecraft.java:535)
    at net.minecraft.client.Minecraft.run(Minecraft.java:378)
    at net.minecraft.client.main.Main.main(Main.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraft.launchwrapper.Launch.launch(Launch.java:135)
    at net.minecraft.launchwrapper.Launch.main(Launch.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at net.minecraftforge.legacydev.Main.start(Main.java:86)
    at net.minecraftforge.legacydev.MainClient.main(MainClient.java:29)
Caused by: java.lang.NoSuchFieldException: field_71449_j
    at java.lang.Class.getDeclaredField(Class.java:2070)
    at net.minecraftforge.fml.relauncher.ReflectionHelper.findField(ReflectionHelper.java:160)
    ... 50 more


A detailed walkthrough of the error, its code path and all known details is as follows:
---------------------------------------------------------------------------------------

-- System Details --
Details:
    Minecraft Version: 1.12.2
    Operating System: Windows 10 (amd64) version 10.0
    Java Version: 1.8.0_291, Oracle Corporation
    Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation
    Memory: 45485224 bytes (43 MB) / 457703424 bytes (436 MB) up to 932184064 bytes (889 MB)
    JVM Flags: 0 total;
    IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0
    FML: MCP 9.42 Powered by Forge 14.23.5.2855 5 mods loaded, 5 mods active
    States: 'U' = Unloaded 'L' = Loaded 'C' = Constructed 'H' = Pre-initialized 'I' = Initialized 'J' = Post-initialized 'A' = Available 'D' = Disabled 'E' = Errored

    | State | ID         | Version      | Source                                                             | Signature |
    |:----- |:---------- |:------------ |:------------------------------------------------------------------ |:--------- |
    | LCHI  | minecraft  | 1.12.2       | minecraft.jar                                                      | None      |
    | LCHI  | mcp        | 9.42         | minecraft.jar                                                      | None      |
    | LCHI  | FML        | 8.0.99.99    | forge-1.12.2-14.23.5.2855_mapped_snapshot_20171003-1.12-recomp.jar | None      |
    | LCHI  | forge      | 14.23.5.2855 | forge-1.12.2-14.23.5.2855_mapped_snapshot_20171003-1.12-recomp.jar | None      |
    | LCHE  | examplemod | 1.0          | main                                                               | None      |

    Loaded coremods (and transformers):
    GL info: ' Vendor: 'Intel' Version: '4.3.0 - Build 20.19.15.5171' Renderer: 'Intel(R) HD Graphics 4600'
 
7,099
324
1,510
Такую фичу уже сделали:
ReAuth
 
34
2
4
Можно было исходник Session посмотреть для понимания аргументов конструктора.

На работоспособность не проверял.
Java:
class Scratch {

public static void createNewSession(String username) {
String uuid = UUID.randomUUID().toString().replace("-", "");
Session session = new Session(username, uuid, "SESSION_ID", "mojang");

try {
setSession(session);
} catch (ReflectiveOperationException e) {
LogManager.getLogger().error("Failed to set new session", e);
}
}

public static void setSession(Session session) throws ReflectiveOperationException {
Field field = ReflectionHelper.findField(Minecraft.class, "field_71449_j", "session"); // SRG & MCP names

if(!field.isAccessible()) {
field.setAccessible(true);
removeFinalFlag(field);
}

field.set(Minecraft.getMinecraft(), session);
}

public static void removeFinalFlag(Field field) throws ReflectiveOperationException {
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
}
}
Используйте на свой страх и риск. Автор не несёт ответственности за причинённый ущерб. 😏
Проблему решил, вместо

Field field = ReflectionHelper.findField(Minecraft.class, "field_71449_j", "session");

Поставить

Field field = ReflectionHelper.findField(Minecraft.class, "session", "field_71449_j");
 
Сверху