Java:如何从静态上下文中获取当前类的类对象? [英] Java: How to get a class object of the current class from a static context?

查看:121
本文介绍了Java:如何从静态上下文中获取当前类的类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个记录函数,该函数将调用对象作为参数.然后,我对其调用getClass().getSimpleName(),以便可以轻松地将类名称添加到日志条目中,以方便参考.问题是,当我从静态方法调用日志函数时,无法传递"this".我的日志功能看起来像这样:

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:

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");
}

显然do_something_static()无效,因为它是静态的,而"this"不在静态上下文中.我该如何解决?而且我可以不使用反射来做吗(因为我知道会涉及很多开销,因为我记录了大量数据可能会影响性能)

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)

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

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.

谢谢!

推荐答案

您可以添加"Class"作为第一个参数,并重载log方法:

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

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 );
    }
}

输出:

$ 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.

您可以使用stacktrace获取调用类,但是正如您提到的那样,如果您多次调用它,将会产生开销.

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.

但是,如果您创建的是作为类变量,那么如果您恰巧使用此实用程序有1,000个类,那么将只有一个类实例.

But if 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.

像这样的东西会更好(此

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

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 );
    }
}

使用测试:

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");
    }
}

输出

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

请注意声明:

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

这样,无论您使用来自objectA,objectB,objectC还是来自类方法(例如main)的记录器",它们都将具有记录器的一个实例并不重要.

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.

这篇关于Java:如何从静态上下文中获取当前类的类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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