2

To be clear, this question is strictly hypothetical. Personally, I have no Real World need for this behaviour; I discovered it accidentally.

Inspired by: How to make a (static) initializer block strictfp?

If I declare a Java class with strictfp modifier:

public strictfp class PublicStrictfpClass
{
    public double f() { return 2d / 3d; }
}

... then I test using Modifier.isStrict(int):

public static void main(String[] argArr)
{
    if (! Modifier.isStrict(PublicStrictfpClass.class.getModifiers()))
    {
        throw new IllegalStateException("Unreachable code");
    }
}

The above code fails: Method main() throws IllegalStateException. I tried a class declaration with and without method PublicStrictfpClass.f() -- both fail.

Do I misunderstand ... ?

  • The strictfp modifier when used in class declarations?
  • The method Modifier.isStrict(int)?

I am running this code from Linux using the latest patch for OpenJDK 8.

Finally, I did a bunch of Googling before asking this question. The keyword strictfp is very rare in the wild!

kevinarpe
  • 20,319
  • 26
  • 127
  • 154
  • 1
    Hmm, `isStrict()` just does bitmasking, but `getModifiers()` is a native method / hotspot intrinsic. Maybe it worked at one point, then stopped working and nobody noticed or cared (or it never worked). – Kayaman Jan 07 '22 at 15:51
  • 1
    It's not only rare in the wild, it's functionality was also removed in Java 17, so it should be avoided all together. – Toni Nagy Jan 07 '22 at 15:54
  • 1
    I doubt either that it never worked, or that it stopped working at one point; rather, the spec for what it does is subtly different to what one might think it should do. Specifically, it refers to the modifiers in *the class*, not in *the source code*, and the `strictfp` modifier ceases to be attached to the class during compilation. Per `javap -c`, it seems as if the compiler outputs bytecode in which the `strictfp` modifier applies to every constructor and method in the class, but not the class itself. – kaya3 Jan 07 '22 at 16:25
  • 1
    Well I don't *actually* think it was broken from the beginning, but since we're putting this much effort into `strictfp`, why not offer some wild theories. – Kayaman Jan 07 '22 at 16:30

1 Answers1

4

It's probably because the class modifiers in the class file do not include the strictfp (don't know why, must ask Java developers). This is what the getModifiers() method looks into, its documentation states: "The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface". (so no mentioning of strictfp)

You can still get the modifiers of the method f. The method modifiers do include strictfp:

Modifier.isStrict(PublicStrictfpClass.class.getMethod("f").getModifiers())
M A
  • 71,713
  • 13
  • 134
  • 174
  • 2
    Docs link for the quote: https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getModifiers-- – kaya3 Jan 07 '22 at 16:28