0

I am learning Java Reflection, and wass playing around with the java.lang.Reflection class. Here is the code I wrote in a class called Driver

Method[] method = Dummy.class.getMethods();

System.out.println("MEthods");
    for (int i = 0; i < method.length; i++) {
        System.out.println("Name: " + method[i].getName());
        System.out.println("Declaring Class: " + method[i].getDeclaringClass());
        System.out.println("ToGenericString: " + method[i].toGenericString());
        System.out.println("Modifiers: " + method[i].getModifiers());
        System.out.println();
    }

Here is the Dummy class

public class Dummy {
    public int b(){return 0;}
}

I would get output like the following

Name: b
Declaring Class: class Dummy
ToGenericString: public int Dummy.b()
Modifiers: 1

Name: hashCode
Declaring Class: class java.lang.Object
ToGenericString: public native int java.lang.Object.hashCode()
Modifiers: 257

Name: notifyAll
Declaring Class: class java.lang.Object
ToGenericString: public final native void java.lang.Object.notifyAll()
Modifiers: 273

//etc

My question is: Why do the Object inherited methods such as wait(), notify() hashcode() etc have over 270+ modifiers whereas my ethod b() only has 1, interestingly enough toString() also has 1

martinomburajr
  • 1,235
  • 14
  • 29
  • 9
    Read the documentation of `getModifiers()`, it is not a number, its a code (a bitset in particular). `hashcode` is native (256) and public (1) resulting in 257. `toString` has only public (1) resulting in 1, `notify` is public, native, final (16), giving 273. The values/constants are documented in `java.reflect.Modifier`. – CoronA Feb 28 '18 at 07:28
  • 2
    @CoronA I suggest you make your Comment an Answer so that it can be accepted to close this Question. – Basil Bourque Feb 28 '18 at 07:34
  • Suggested duplicate: [Comparing modifiers in Java](https://stackoverflow.com/questions/17199409/comparing-modifiers-in-java) – Erwin Bolwidt Feb 28 '18 at 07:37
  • @CoronA sweet thanks, would've never have guessed! – martinomburajr Feb 28 '18 at 07:45

1 Answers1

1

The result of getModifiers is not a number but a code (a bitset in particular).

Each modifier has a value, e.g.: - public is 1 - final is 16 - native is 256

You have to combine them with the bitwise or operation (which is in this case similar to the add operation).

To get a complete list of modifiers read the documentation and the source code of Modifier.

  • toString is public (1) => 1
  • hashcode is public (1) and native (256) => 257
  • notifyAll is public (1) and final (16) and native (256) => 273
CoronA
  • 7,717
  • 2
  • 26
  • 53