是否可以在使用反射时创建匿名类? [英] Is it possible to create an anonymous class while using reflection?

查看:162
本文介绍了是否可以在使用反射时创建匿名类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在对象运行初始化程序之前在运行时实现一个方法。这将允许我设置初始化期间使用的字段。

I would like to be able to implement a method at runtime that is called before an object runs the initializers. This will allow me to set fields that are used during initialization.

以下是一个例子:

class A {
  public A() {
    initialize();
  }
  public void initialize() { }
}

class B extends A {
  public String message;
  {
    System.out.println(message);
  }
}

public class MainClass {
  public static void main(final String[] args) throws Exception {

    Class<A> aClass = (Class<A>)Class.forName(args[0]);
    // what's next in order to something like this even though
    // I don't know what subclass of A was passed in as an
    // argument above 
    A a = aClass.newInstance()
    {
      public void initialize() {
        this.message = args[1];
      }
    };
  }
}

我可能最终会使用方面,但我会想知道是否有纯粹的Java方式。

I will probably end up using aspects, but I would like to know if there is a pure Java way.

推荐答案

你要做的是创建一个新的匿名内部类这是您在运行时只知道的某个类的子类。反思无法解决这个问题。

What you are trying to do would entail creating a new anonymous inner class that is a subclass of some class that you only know at runtime. Reflection cannot solve this problem.

动态代理可能......如果你试图实现一个动态加载的接口。

Dynamic proxies might ... if you were trying to implement a dynamically loaded interface.

唯一的其他我能想到的方法是使用BCEL或动态源代码生成/编译。两者都会变得非常复杂。并且都算不上纯Java。

The only other approaches I can think of are to use BCEL or dynamic source code generation / compilation. And both are going to be very complicated. And neither count as pure Java.

我的建议是重新审视你想要实现的目标。 (你的问题没有暗示可能是什么,所以很难提供任何实际的建议。)

My advice would be to take a fresh look at what it is you are trying to achieve. (Your question gives no hints as to what that might be, so it is hard to offer any practical suggestions.)

这篇关于是否可以在使用反射时创建匿名类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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