如何在Java中获取调用类的名称? [英] How to get the name of the calling class in Java?

查看:43
本文介绍了如何在Java中获取调用类的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这件事上得到一些帮助,

I would like some help on this matter,

示例:

public class A {
    private void foo() {
        //Who invoked me?
    }
}

public class B extends A {}

public class C extends A {}

public class D {
     C.foo();
}

基本上就是这个场景.我的问题是方法 foo() 如何知道谁在调用它?

This is basically the scenario. My question is how can method foo() know who is calling it?

EDIT:基本上我正在尝试做一个数据库层,并且在 class A 中,我将创建一个将生成 SQL 语句的方法.这些语句是通过获取调用class 的所有public 属性的值动态生成的.

EDIT: Basically I am trying to do a database Layer, and in class A I will create a method that will generate SQL statements. Such statements are dynamically generated by getting the values of all the public properties of the calling class.

推荐答案

最简单的方法如下:

String className = new Exception().getStackTrace()[1].getClassName();

但实际上应该没有必要这样做,除非出于某些记录目的,因为这是一项相当昂贵的任务.它是什么,您认为这是解决方案的问题?我们可能会提出 - 更好的建议.

But in real there should be no need for this, unless for some logging purposes, because this is a fairly expensive task. What is it, the problem for which you think that this is the solution? We may come up with -much- better suggestions.

编辑:您的评论如下:

基本上我正在尝试做一个数据库层,在 A 类中我将创建一个将生成 sql 语句的方法,这些语句是通过获取调用类的所有公共属性的值来动态生成的.

然后我强烈建议寻找现有的ORM 库,例如休眠、iBatisa> 或您喜欢的任何 JPA 实现.

I then highly recommend to look for an existing ORM library, such as Hibernate, iBatis or any JPA implementation to your taste.

这篇关于如何在Java中获取调用类的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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