我有一个抽象的A类,即
public abstract class A {
private final Object o;
public A(Object o) {
this.o = o;
}
public int a() {
return 0;
}
public abstract int b();
}
Run Code Online (Sandbox Code Playgroud)
我有一个子类B,即
public class B extends A {
public B(Object o) {
super(o);
}
@Override
public int a() {
return 1;
}
@Override
public int b() {
return 2;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在执行以下代码:
Constructor c = B.class.getDeclaredConstructor(Object.class);
B b = (B) c.newInstance(new Object());
Run Code Online (Sandbox Code Playgroud)
并且在调用newInstance时获得InstantiationException,更具体地说:
java.lang.InstantiationException
at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
Run Code Online (Sandbox Code Playgroud)
我不知道为什么我收到例外.我已经查看了一些其他类似的问题,并在调用超级构造函数或者父类的抽象性质的问题时看到了有关最终变量用法的事情,但我找不到为什么这种特殊情况抛出InstantiationException的明确答案.有任何想法吗?
假设我有一个抽象类:
abstract class Foo extends Bar {
public abstract int foo();
}
Run Code Online (Sandbox Code Playgroud)
我想在运行时扩展以创建一个Class对象.希望是我可以拥有一个动态生成的类:
class FooImpl extends Foo {
@Override
public int foo() {
return 5;
}
}
Run Code Online (Sandbox Code Playgroud)
这将由一个Class对象表示,然后我可以使用反射来创建新的实例.关键是我想在运行时决定方法foo()的返回值.我的想法是使用ASM为类创建字节码,然后在ClassLoader对象上使用反射来定义类.
使用ASM然后在生成的字节上反映方法ClassLoader #defineClass是在运行时使用非硬编码值实现抽象方法的最佳方法吗?
如果是的话,我将如何做到这一点.我的直觉是利用ASMifierClassVisitor,但我不确定这样做的确切方法.我知道如果所有其他方法都失败了,我可以手动完成定义特定类所需的JVM指令,但我觉得必须有一个更简单的方法.
如果不是,最好的方法是什么,我将如何使用最佳方式?
编辑:我检查了所有答案,我认为它们都不是我想要的.我最终创建了一个与ASM谈论的小实现.我想我应该在这里发布:
import org.objectweb.asm.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
/**
* Created by IntelliJ IDEA.
* User: Matt
* Date: 9/17/11
* Time: 12:42 PM
*/
public class OverrideClassAdapter extends ClassAdapter {
private final HashMap<String, Object> code;
private final String …Run Code Online (Sandbox Code Playgroud) 我有一组表,其中包含用户创建和投票的内容.
表content_a
id /* the id of the content */
user_id /* the user that contributed the content */
content /* the content */
Run Code Online (Sandbox Code Playgroud)
表content_b
id
user_id
content
Run Code Online (Sandbox Code Playgroud)
表content_c
id
user_id
content
Run Code Online (Sandbox Code Playgroud)
表投票
user_id /* the user that made the vote */
content_id /* the content the vote was made on */
content_type_id /* the content type the vote was made on */
vote /* the value of the vote, either +1 or -1 */
Run Code Online (Sandbox Code Playgroud)
我希望能够选择一组用户,并根据他们制作的内容的总票数对它们进行排序.例如, …