'getClass()' 在 Byte Buddy 示例中
'getClass()' in Byte Buddy Example
我从 Byte Buddy 站点获取了以下示例代码并将其粘贴到 Eclipse 中:
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
getClass()
被语法检查器错误显示消息:
Cannot make a static reference to the non-static method getClass() from the type Object.
如何解决这个问题?
我假设您已将代码复制到静态 main 方法中。
由于该方法是静态的,您不能使用实例方法getClass()
。
改为像这样访问类加载器:
YourClassName.class.getClassLoader()
中找到有关 Class 文字的更多信息
此代码是在静态方法中指定的 - 您没有包含它,但 "Cannot make a static reference" 是赠品。
将您的代码移动到一个实例方法中,然后从那里调用它。如果您当前是通过 main
方法执行此操作,请将其更改为以下内容。
public class ExampleClass {
public static void main(String[] args) {
// this method is static - see the key word in the signature
new ExampleClass().execute();
}
public void execute() {
// this is an instance method
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
}
}
或者,您可以将获取 class 的方式从 getClass()
更改为静态引用 ExampleClass.class
.
我从 Byte Buddy 站点获取了以下示例代码并将其粘贴到 Eclipse 中:
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
getClass()
被语法检查器错误显示消息:
Cannot make a static reference to the non-static method getClass() from the type Object.
如何解决这个问题?
我假设您已将代码复制到静态 main 方法中。
由于该方法是静态的,您不能使用实例方法getClass()
。
改为像这样访问类加载器:
YourClassName.class.getClassLoader()
中找到有关 Class 文字的更多信息
此代码是在静态方法中指定的 - 您没有包含它,但 "Cannot make a static reference" 是赠品。
将您的代码移动到一个实例方法中,然后从那里调用它。如果您当前是通过 main
方法执行此操作,请将其更改为以下内容。
public class ExampleClass {
public static void main(String[] args) {
// this method is static - see the key word in the signature
new ExampleClass().execute();
}
public void execute() {
// this is an instance method
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.make()
.load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
}
}
或者,您可以将获取 class 的方式从 getClass()
更改为静态引用 ExampleClass.class
.