Java:如何从静态上下文中获取当前类的类对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1307477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:04:34  来源:igfitidea点击:

Java: How to get a class object of the current class from a static context?

javareflectionlogging

提问by DivideByHero

I have a logging function that takes the calling object as a parameter. I then call getClass().getSimpleName() on it so that I can easily get the class name to add to my log entry for easy reference. The problem is that when I call my log function from a static method, I can't pass in "this". My log function looks something like this:

我有一个将调用对象作为参数的日志记录函数。然后我对其调用 getClass().getSimpleName() 以便我可以轻松地将类名添加到我的日志条目中以便于参考。问题是当我从静态方法调用我的日志函数时,我无法传入“this”。我的日志功能如下所示:

public static void log(Object o, String msg){
  do_log(o.getClass().getSimpleName()+" "+msg);
}
public void do_something(){
  log(this, "Some message");
}

But let's say I want to log from a static function:

但是假设我想从静态函数登录:

public static void do_something_static(){
  log(this, "Some message from static");
}

Obviously do_something_static() won't work because it is static and "this" is not in a static context. How can I get around this? And can I do it without using reflection (since I understand there is a lot of overhead involved and it might affect performance since I log a LOT of data)

显然 do_something_static() 不起作用,因为它是静态的,而“this”不在静态上下文中。我怎样才能解决这个问题?我可以在不使用反射的情况下做到这一点吗(因为我知道涉及很多开销并且它可能会影响性能,因为我记录了大量数据)

I know I can probably hard-code the current class into the call somehow, but I'm sure that when I move the function to another class, I will forget to update the hard-coded reference and it will no longer be correct.

我知道我可以以某种方式将当前类硬编码到调用中,但是我确信当我将函数移到另一个类时,我会忘记更新硬编码的引用,它不再正确。

Thanks!

谢谢!

采纳答案by OscarRyz

You could add "Class" as first parameter and overload the log method:

您可以添加“Class”作为第一个参数并重载日志方法:

public class SomeClass {
    // Usage test:
    public static void main( String [] args ) {
        log( SomeClass.class, "Hola" );
        log( new java.util.Date(), "Hola" );
    }

    // Object version would call Class method... 
    public static void log( Object o , String msg ) {
        log( o.getClass(), msg );
    }
    public static void log( Class c ,  String message ) {
        System.out.println( c.getSimpleName() + " " + message );
    }
}

Output:

输出:

$ java SomeClass
SomeClass Hola
Date Hola

But it feels just bad to have the calling class passed as the first argument. Here's where object oriented model comes into play as opposite of "procedural" style.

但是将调用类作为第一个参数传递感觉很糟糕。这就是面向对象模型与“过程”风格相反的地方。

You could get the calling class using the stacktrace, but as you metioned, there would be an overhead if you call it thousands of times.

您可以使用堆栈跟踪获取调用类,但正如您所提到的,如果您调用它数千次,将会产生开销。

Butif you create is as class variable, then there would be only one instance for class if you happen to have 1,000 classes using this utility, you would have at most 1,000 calls.

但是,如果您创建的是类变量,那么如果您碰巧有 1,000 个使用此实用程序的类,那么将只有一个类实例,您最多将有 1,000 次调用。

Something like this would be better ( subtle variation of this otheranswer) :

这样的事情会更好(其他答案的细微变化):

public class LogUtility {

    private final String loggingFrom;

    public static LogUtility getLogger() {
        StackTraceElement [] s = new RuntimeException().getStackTrace();
        return new LogUtility( s[1].getClassName() );
    }

    private LogUtility( String loggingClassName ) {
        this.loggingFrom = "("+loggingClassName+") ";
    }

    public void log( String message ) {
        System.out.println( loggingFrom + message );
    }
}

Usage test:

使用测试:

class UsageClass {
    private static final LogUtility logger = LogUtility.getLogger();

    public static void main( String [] args ) {

        UsageClass usageClass = new UsageClass();

        usageClass.methodOne();
        usageClass.methodTwo();
        usageClass.methodThree();

    }
    private void methodOne() {
        logger.log("One");
    }
    private void methodTwo() {
        logger.log("Two");
    }
    private void methodThree() {
        logger.log("Three");
    }
}

OUtput

输出

$ java UsageClass
(UsageClass) One
(UsageClass) Two
(UsageClass) Three

Notice the declaration:

注意声明:

....
class UsageClass {
    // This is invoked only once. When the class is first loaded.
    private static final LogUtility logger = LogUtility.getLogger();
....

That way, it doesn't matter if you use the "logger" from objectA, objectB, objectC or from a class method ( like main ) they all would have one instance of the logger.

这样,如果您使用来自 objectA、objectB、objectC 或类方法(如 main)的“记录器”并不重要,它们都将具有记录器的一个实例。

回答by akf

You should hard code the class into the call in the short term. If you think you will need this in a variety of places in your project, as it is static, you should encapsulate it and have it take the class as a param.

您应该在短期内将该类硬编码到调用中。如果您认为在项目中的各个地方都需要它static,那么您应该封装它并让它将类作为参数。

public static void do_something_static(Class callingClass){
  log(callingClass, "Some message from static");
}

回答by Jo?o Silva

Well, if you really don't want to hardcode something like ClassName.class, then you can try to infer the class by traversing the stacktrace. Fortunately, someone alreadydid it : ). Also, consider using a logger that allows you to log something without specifying the calling object.

好吧,如果你真的不想硬编码类似的东西ClassName.class,那么你可以尝试通过遍历堆栈跟踪来推断类。幸运的是,有人已经做到了:) 。此外,请考虑使用一个记录器,它允许您在不指定调用对象的情况下记录某些内容。

回答by Marian

Alter method logto:

将方法更改log为:

public static void log(Class c, String msg){
  do_log(c.getSimpleName()+" "+msg);
}

and if do_something_staticis in class MyClassWithStaticsthen do_something_staticwould become:

如果do_something_static在课堂上,MyClassWithStatics那么do_something_static将变成:

public static void do_something_static(){
  log(MyClassWithStatics.class, "Some message from static");
}

回答by dfa

querying the stacktrace maybe worty for your problem. You have 3 possible approachs.

查询堆栈跟踪可能对您的问题有用。您有 3 种可能的方法。

Exception#getStackTrace()

异常#getStackTrace()

Just create an exception instance and get the first frame:

只需创建一个异常实例并获取第一帧:

static String className() {
    return new RuntimeException().getStackTrace()[0].getClassName();
}

Thread

线

Using Thread is even easier:

使用 Thread 更容易:

static String className2() {
    return Thread.currentThread().getStackTrace()[1].getClassName();
}

these two approachs have the disadvantage that you cannot reuse them. So you may want to define an Helper class for that:

这两种方法的缺点是你不能重用它们。所以你可能想为此定义一个 Helper 类:

class Helper {

    public static String getClassName() {
        return Thread.currentThread().getStackTrace()[2].getClassName();
    }
} 

now you can obtain your class name programmatically, without hardcoding the class name:

现在您可以通过编程方式获取您的类名,而无需对类名进行硬编码:

public static void log(Object o, String msg){
    do_log(Helper.getCClassName() + "  " + msg);
}

回答by Thorbj?rn Ravn Andersen

Instead of "this" use "MyClass.class" and let your log method treat class objects without getClass().

使用“MyClass.class”代替“this”,并让您的日志方法在没有 getClass() 的情况下处理类对象。

But instead of doing this yourself, consider letting the log framework do it.

但与其自己做,不如考虑让日志框架来做。

回答by Zed

Replace your static functions with non-static ones. Instead of

用非静态函数替换静态函数。代替

Utils.do_something(...)

do

new Utils().do_something(...)

回答by LeoFarage

Wouldn't implementing some sort of Singletondo what you need?

不会实现某种单例做你需要的吗?

public class LogUtility {

    private final String loggingFrom;
    private static LogUtility instance;

    public static LogUtility getLogger() {
        if(instance == null)
            this.instance = new LogUtility();
        StackTraceElement [] s = new RuntimeException().getStackTrace();
        this.instance.setLoggingFrom(s[1].getClassName())
        return this.instance;
    }

    private LogUtility() {}

    private void setLoggingFrom(String loggingClassName){
        this.loggingFrom = loggingClassName;
    }

    public void log( String message ) {
        System.out.println( loggingFrom + message );
    }
}

Usage (anywhere in your project):

用法(在您的项目中的任何地方):

LogUtility.getLogger().log("Message");