zduny
zduny

Reputation: 2541

Force static part of class to run without instantiation

I have a class:

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

And the problem is it is only run if I instantiate that class.

How can I force it to be run no matter what?

Upvotes: 3

Views: 980

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

Use

Class.forName("TextViewAttachedProperties");

The javadoc states

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.

where true specifies

initialize - whether the class must be initialized

When the class is initialized, the static initializers will be executed and static fields will be initialized.

There are other ways to initialize a type such as accessing a static non-constant variable of the type, invoking a static method of the class, or instantiating the class. They are all described in the Java Language Specification. More or less.

Upvotes: 3

FrobberOfBits
FrobberOfBits

Reputation: 18002

Static initialization blocks run when the JVM first sees a mention of the class. That is, when the class gets loaded.

You don't need to create an instance, but you do need to mention/reference the class in some way. There are a number of ways you can do this that will do the trick.

Upvotes: 1

Related Questions