我有一个类:
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");
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/