java - 强制类的静态部分在没有实例化的情况下运行

标签 java static

我有一个类:

public class TextViewAttachedProperties {
    public static final String NAMESPACE = "http://schemas.android.com/apk/lib/com.zworks.mvvmandroid";

    private static final Handler uiHandler = new Handler(Looper.getMainLooper());

    private static final String DATA_CONTEXT = "DataContext";
    private static final String TEXT = "Text";

    private static final Listener<PropertyChangedEventArgs<String>> textChanged = new Listener<PropertyChangedEventArgs<String>>() {

        @Override
        public void onEvent(final PropertyChangedEventArgs<String> args) {
            final TextView element = (TextView) args.getSource();

            if (element != null && args.getNewValue() != null)
                uiHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        element.setText(args.getNewValue());
                    }
                });
        }
    };

    // This two statements have side effects I'm counting on to execute
    private static final AttachedProperty<Object> dataContext = AttachedProperty
        .newProperty(DATA_CONTEXT, NAMESPACE, TextView.class, null); 
    private static final AttachedProperty<String> text = AttachedProperty
        .newProperty(TEXT, NAMESPACE, TextView.class, "", textChanged);
}

问题是它只有在我实例化该类时才会运行。

无论如何我怎样才能强制它运行?

最佳答案

使用

Class.forName("TextViewAttachedProperties");

javadoc

Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to:

Class.forName(className, true, currentLoader)

where currentLoader denotes the defining class loader of the current class.

其中 true 指定

initialize - whether the class must be initialized

当类被初始化时,static 初始化器将被执行,static 字段将被初始化。

还有其他方法可以初始化类型,例如访问类型的 static 非常量变量、调用类的 static 方法或实例化类. They are all在 Java 语言规范中描述。 More or less.

关于java - 强制类的静态部分在没有实例化的情况下运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23301701/

相关文章:

C#静态方法调用结果出错?

c++ - 通过一次安装生成静态库和可执行文件(autoconf)

java - 为什么有两种不同的方式来创建内部类的实例?

java - 在树形图中设置树形图的值?

java - FixedThreadPool 和 ExecutorCompletionService 的 OutOfMemory 错误

java - 发送大文件的最佳方式

java.lang.IllegalStateException : No value for key [org. hibernate.impl.SessionFactoryImpl] 与 AOP

Java字符串文本规范化重复韩文字符

C# 从 App.xaml.cs 访问 WPF 主窗口中的静态属性时导致这种奇怪行为的原因

c# - 如何用抽象基础修复 "CA1810: Initialize reference type static fields inline"...?