如何匿名实例化 Java 中存储在 Class 对象中的抽象类? [英] How to anonymously instantiate an abstract class stored in a Class object in Java?

查看:18
本文介绍了如何匿名实例化 Java 中存储在 Class 对象中的抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个抽象类,你可以通过派生一个具体的匿名类来实例化它.这是一个例子:

If you have an abstract class you can instantiate it by deriving an concrete anonymous class. This is an example:

abstract class A {
     abstract void hello ();
}

A say = new A () { void hello () { System.out.println ("hello"); } }

say.hello(); // -> hello

如果类存储在 Class 对象中,如何做同样的事情?下面是一个例子:

How to do the same if the class is stored in a Class object? Here is an example:

// -*- compile-command: "javac anon.java && java anon"; -*-

class anon
{
    anon () throws Exception {}

    abstract class AbstractClass
    {
        AbstractClass () throws Exception {}
        abstract void id ();
    }

    AbstractClass x = new AbstractClass ()
        {
            void id () { System.out.println ("X"); }
        };

    Class<AbstractClass> abstractclass 
        = (Class<AbstractClass>)Class.forName ("anon$AbstractClass");

    AbstractClass y = abstractclass.getConstructor().newInstance();

    public static void main (String argv[]) throws Exception
    {
        anon main = new anon();
        main.x.id(); // should print "X"
        main.y.id(); // should print "Y"
    }
}

第一个实例化 (x) 工作正常,但第二个 (y) 失败,因为它试图直接实例化抽象类而不派生具体类.如何在只有 Class 对象的 Java 中执行此操作?

The first instantiation (x) works fine but the second (y) fails because it tries to instantiate the abstract class directly without deriving a concrete class. How can I do this in Java having only a Class object?

推荐答案

您可能对匿名类的工作原理有误解.匿名类实际上是一个普通类,就像任何其他类一样,并且有自己的类文件.Java-the-language 仅为此提供了一些语法糖,并允许通过在其自己的文件中声明常规命名的顶级类来精确模拟某些内容的不太冗长的语法.这就是为什么您会发现 Reflection API 对您想要实现的目标毫无用处.基本上,您希望动态创建一个没有其类文件的类.为此,您需要一个合适的库,例如 javassist.

You may have a misunderstanding on how exactly anonymous classes work. An anonymous class is in fact a regular class just like any other and has its own class file. Java-the-language only provides some syntactic sugar over this and allows a less verbose syntax for something that you can exactly mimic by declaring a regular named top-level class in its own file. This is why you will find the Reflection API useless for what you want to achieve. Basically, you want to dynamically create a class that doesn't have its class file. For this you need a suitable library, such as javassist.

这篇关于如何匿名实例化 Java 中存储在 Class 对象中的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆