javasisst - 由于 "missing" 字段而未编译
javasisst - Not compiling due to "missing" field
我有以下代码:
CtClass player = ClassPool.getDefault().get("org.spongepowered.api.entity.living.player.Player");
CtField toAdd = CtField.make("public java.lang.String nick = null;", player);
player.addField(toAdd);
后来我有这个:
e.getTargetEntity()/*this function returns a class that implements Player*/
Player.nick = e.getTargetEntity().getName();
如何编译这段代码? eclipse 和 maven 都抛出编译异常,因为很明显,他们不知道 Player.nick 是一个字段这一事实。感谢任何帮助。
您必须使用反射来设置字段。
package hello;
import com.thoughtworks.xstream.XStream;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
class Player {
}
class Main {
public static void main(String[] args) throws Exception {
CtClass player = ClassPool.getDefault().get("hello.Player");
CtField toAdd = CtField.make("public java.lang.String nick = null;", player);
player.addField(toAdd);
Class patchedPlayer = player.toClass();
Object o = patchedPlayer.newInstance();
patchedPlayer.getField("nick").set(o, "hello, Player");
String s = new XStream().toXML(o);
System.out.println(s);
}
}
将打印
<hello.Player>
<nick>hello, Player</nick>
</hello.Player>
还要确保 e.getTargetEntity()
returns 补丁 class 的对象,而不是原始对象。
我有以下代码:
CtClass player = ClassPool.getDefault().get("org.spongepowered.api.entity.living.player.Player");
CtField toAdd = CtField.make("public java.lang.String nick = null;", player);
player.addField(toAdd);
后来我有这个:
e.getTargetEntity()/*this function returns a class that implements Player*/
Player.nick = e.getTargetEntity().getName();
如何编译这段代码? eclipse 和 maven 都抛出编译异常,因为很明显,他们不知道 Player.nick 是一个字段这一事实。感谢任何帮助。
您必须使用反射来设置字段。
package hello;
import com.thoughtworks.xstream.XStream;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
class Player {
}
class Main {
public static void main(String[] args) throws Exception {
CtClass player = ClassPool.getDefault().get("hello.Player");
CtField toAdd = CtField.make("public java.lang.String nick = null;", player);
player.addField(toAdd);
Class patchedPlayer = player.toClass();
Object o = patchedPlayer.newInstance();
patchedPlayer.getField("nick").set(o, "hello, Player");
String s = new XStream().toXML(o);
System.out.println(s);
}
}
将打印
<hello.Player>
<nick>hello, Player</nick>
</hello.Player>
还要确保 e.getTargetEntity()
returns 补丁 class 的对象,而不是原始对象。