0

我有一个基本的抽象记录器类,它有一个实例变量,我希望在创建代码时由派生类自动设置。所以这里是基类:

abstract public class CLog 
{
    /** Maintains the call stack level for each thread */
    private static HashMap<Integer, Integer> callStackLevel = new HashMap<Integer, Integer>();

    /** Static instance to be set by the derived class */
    private static CLog instance = null;

    /** Logs in verbose */
    public static void v(String message) { if(instance != null) instance.verbose(getMessage(message)); }
    /** Logs in debug */
    public static void d(String message) { if(instance != null) instance.debug(getMessage(message)); }
    /** Logs in informational */
    public static void i(String message) { if(instance != null) instance.info(getMessage(message)); }
    /** Logs in warning */
    public static void w(String message) { if(instance != null) instance.warn(getMessage(message)); }
    /** Logs in error */
    public static void e(String message) { if(instance != null) instance.error(getMessage(message)); }

    /**
     * Calculates the message (with header)
     */
    private static String getMessage(String message)
    {
        ...
    }

    /** Constructor sets instance */
    protected CLog() { instance = this; }

    /** Logs in verbose */
    protected abstract void verbose(String message);
    /** Logs in debug */
    protected abstract void debug(String message);
    /** Logs in informational */
    protected abstract void info(String message);
    /** Logs in warning */
    protected abstract void warn(String message);
    /** Logs in error */
    protected abstract void error(String message);
}

我为一个 android 记录器创建了派生类。我希望它自动调用构造函数,但似乎这不起作用,因为我的所有日​​志记录函数都没有产生任何结果。

public class AndroidLog extends CLog 
{
    protected static AndroidLog derived = new AndroidLog();

    @Override
    protected void debug(String message) {
        Log.d("Crystal", message);
    }

    @Override
    protected void error(String message) {
        Log.e("Crystal", message);
    }

    @Override
    protected void info(String message) {
        Log.i("Crystal", message);
    }

    @Override
    protected void verbose(String message) {
        Log.v("Crystal", message);
    }

    @Override
    protected void warn(String message) {
        Log.w("Crystal", message);
    }
}

为什么这不起作用?当我在基类中调用静态函数时,我没有得到任何日志。

无论如何只要编辑 AndroidLog 类或通过在不依赖 AndroidLog 的 CLog 类中进行编辑来完成这项工作?

4

2 回答 2

2

类的存在AndroidLog不会导致它自己引导!

In Java classes are loaded and initialized when they are used, not before! So unless any class of yours somewhere references AndroidLog in some relevant way, it will never be loaded, it's static fields never initialized and its constructor will never be called.

于 2011-04-20T07:37:03.810 回答
0

Another important aspect is the fact that private static class members are not inherited! Your AndroidLog class will not have access to any of the private static members in the base class.

于 2011-04-20T11:34:37.520 回答