0

I am learning about reflection and I found some snippet that looks like this:

private static int modifierFromString(String s) {
    int m = 0x0;
    if ("public".equals(s))           m |= Modifier.PUBLIC;
    else if ("protected".equals(s))   m |= Modifier.PROTECTED;
    else if ("private".equals(s))     m |= Modifier.PRIVATE;
    else if ("static".equals(s))      m |= Modifier.STATIC;
    else if ("final".equals(s))       m |= Modifier.FINAL;
    else if ("transient".equals(s))   m |= Modifier.TRANSIENT;
    else if ("volatile".equals(s))    m |= Modifier.VOLATILE;
    return m;
}

I am very confused, what does the m |= Modifier.PUBLIC mean and can I use m = Modifier.PUBLIC?

Oldskool
  • 34,211
  • 7
  • 53
  • 66
zmychou
  • 25
  • 1
  • 5
  • It's a [bitwise or](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html), which is used to combine multiple values. But in this case, each result is in a separate `else`, so you can technically modify it as you suggested. I'm actually a bit surprised to see such code from an [official tutorial](https://docs.oracle.com/javase/tutorial/reflect/member/fieldModifiers.html). – shmosel May 15 '16 at 05:27
  • `|=` is a Compound Assignment Operator, combining `=` (assignment) and `|` (bit-wise OR). – Andreas May 15 '16 at 05:27

1 Answers1

2

m |= Modifier.PUBLIC; is equivalent to m = m | Modifier.PUBLIC;, which means you perform bit-wise OR on m and Modifier.PUBLIC and assign the result back to m.

Since your method executes just one such assignment to m and m is initialized to 0, you can replace it with simple assignment (m = Modifier.PUBLIC;) and get the same output.

Eran
  • 387,369
  • 54
  • 702
  • 768