考虑下面的代码:
public interface IRegistryClass
{
public IRegistryClass get();
}
public abstract class Skill implements IRegistryClass
{
@Override
public Skill get()
{
return new SkillFake();
}
private final class SkillFake extends Skill
{}
}是否可以在仅随Skill.class提供的情况下调用skill#get()?
常规Java不允许使用class#newInstance()抽象类。问题是:有没有办法?
注意:我不能有static关键字。这件事我需要继承。
编辑:我读过关于不安全的文章--在这种情况下会有帮助吗?我知道你的日常java在这里是没用的。需要一些极端的东西。
发布于 2015-09-22 14:15:31
即使使用Unsafe也无法做到这一点,因为Unsafe.allocateInstance也为抽象类抛出了java.lang.InstantiationException。唯一可能的解决方案是创建一个匿名类,如下所示:
new Skill() {}.get();这并不完全是您想要的,因为匿名类仍然是继承Skill类的新类。但在许多情况下,这是令人满意的。
更新:如果你真的想要一些极端的东西,你可以在运行时旋转匿名类。例如,使用ASM库可以做到这一点:
// Generate subclass which extends existing Skill.class
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
String superClassName = Skill.class.getName().replace('.', '/');
cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER + Opcodes.ACC_FINAL
+ Opcodes.ACC_SYNTHETIC, "anonymous", null, superClassName, null);
// Create constructor which calls superclass constructor
MethodVisitor ctor = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
ctor.visitCode();
// load this
ctor.visitVarInsn(Opcodes.ALOAD, 0);
// call superclass constructor
ctor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClassName, "<init>", "()V", false);
// return
ctor.visitInsn(Opcodes.RETURN);
ctor.visitMaxs(-1, -1);
ctor.visitEnd();
cw.visitEnd();
// Get the Unsafe object
Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
sun.misc.Unsafe UNSAFE = (sun.misc.Unsafe) field.get(null);
// Create new anonymous class
Class<? extends Skill> clazz = UNSAFE.defineAnonymousClass(Skill.class,
cw.toByteArray(), null).asSubclass(Skill.class);
// instantiate new class and call the `get()` method
clazz.newInstance().get();通过这种方式,您可以在运行时创建抽象类的子类(子类不存在于已编译的代码中)。当然应该指出的是,这样的解决方案是,嗯,不安全的。
https://stackoverflow.com/questions/32709110
复制相似问题