Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

android - Why make a method volatile in java?

Why would a method be made volatile? How does making a method volatile change the method's behavior?

Edit: I did a toString() on a Method object returned by a class object (Java Reflection). The return string had a volatile modifier against the method name along with public visibility and void return type. Research yielded only information on volatile for properties. This is why I asked this question.

The method declaration was:

public volatile org.osmdroid.api.IGeoPoint org.osmdroid.views.MapView.getMapCenter()

Code for the Reflection Method:

public static class Test {
    public static void showMethods(Object target) {
        Class<?> clazz = target.getClass();
        for (Method method : clazz.getMethods()) {
            if (method!=null) {
                System.out.println(method.toString());
            }
        }
    }
}

Method invocation:

Test.showMethods(mapView);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I strongly suspect that what you're seeing is a side-effect of the fact that the JLS defines the following bit for fields:

public static final int VOLATILE = 0x00000040;

and the following bit for methods:

static final int BRIDGE = 0x00000040;

Note that they have the same value (the same bit has a different meaning for methods and fields).

If you call e.g. Modifier.toString(int) without, as the documentation suggests:

Note that to perform such checking for a known kind of entity, such as a constructor or method, first AND the argument of toString with the appropriate mask from a method like constructorModifiers or methodModifiers.

then you'll get inappropriate output (including bridge methods, autogenerated for e.g. covariant return type, showing up as 'volatile').

At least the current OpenJDK Method.toString() filters this out; if yours isn't, perhaps you're using a different or older version of the JDK which doesn't do this correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...