如何在Java中获取调用类的名称? [英] How to get the name of the calling class in 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 :基本上我正在尝试做一个数据库层,而在类AI中会创建一个生成SQL语句的方法。这些语句是通过获取调用类的所有公共属性的值动态生成的。
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库,例如 Hibernate , iBatis 或任何 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屋!