获取实例的声明类:可能吗?

时间:2014-04-20 15:49:43

标签: java class reflection instance

有没有办法在运行时检索实例的声明类? 例如:

public class Caller {
    private JFrame frame = new JFrame("Test");
    private JButton button = new JButton("Test me");
    private Callee callee = new Callee();

    public Caller() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(button);

        button.addActionListener(callee.getListener());

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Caller();
    }
}

被叫方:

public class Callee {
    public ActionListener getListener() {
        return new ActionListener() {
        @Override
            public void actionPerformed(ActionEvent e) {
                /* Get the class "Caller" here and invoke its methods */
                /* Something along the lines of: */
                Object button = e.getSource();
                button.getOwnerClass(); //This would return the type Caller
            }
        };
    }
}

“getOwnerClass()”是一个虚构的方法。有没有办法得到与此类似的结果?

1 个答案:

答案 0 :(得分:2)

标准API中没有任何内容可以让您获取此信息。有点不清楚你的意思是什么'宣布上课'或者'所有者类'但是为了这个答案,我假设它是代码创建了对象实例的类(你想要所有者类)。

默认情况下,JVM不会存储此信息。

但是,使用the heap profiler that is packaged along with the JDK distribution,您可以记录分配对象的点的堆栈跟踪,并且可以在不同时间点将此信息写入文件。

它仍然没有给你一个API调用来检索信息,但它表明在技术上可以记录这类信息。

我在Google上搜索了一下,发现有人确实创建了一个使用与堆分析器相同的基本技术的API(java.lang.instrumentation包/ JVMTI接口)

通过一些工作,你应该可以用它来构建一些东西。

该网站有一个很好的例子:

AllocationRecorder.addSampler(new Sampler() {
    public void sampleAllocation(int count, String desc, Object newObj, long size) {
      System.out.println("I just allocated the object " + newObj + 
        " of type " + desc + " whose size is " + size);
      if (count != -1) { System.out.println("It's an array of size " + count); }
    }
});

您应该使用new Exception().getStackTrace()获取堆栈跟踪,删除引用采样器和API类的前几个StackTraceElement对象,然后调用StackTraceElement.getClassName()以获取创建对象实例的类的名称,换句话说,是OwnerClass。