An expression that behaves differently within a static method

I am trying to write an expression or a series of Java source code instructions that, if written inside a method static, are evaluated as null, but if the method is non-static, evaluates to this.

My initial idea was to โ€œoverloadโ€ static and non-static, as shown below:

public class test {
  public void method1() {
    System.out.println(getThisOrNull());
  }

  public static void method2() {
    System.out.println(getThisOrNull());
  }

  private static Object getThisOrNull() {
    return null;
  }

  private Object getThisOrNull() {
    return this;
  }

  public static void main(String[] args) {
    test t = new test();
    System.out.println(t);
    t.method1();
    t.method2();
  }
}

Unfortunately, this is actually not legal Java, you cannot "overload" it, and it just gives a compiler error:

test.java:14: error: method getThisOrNull() is already defined in class test
  private Object getThisOrNull() {
                 ^
1 error

, , , , , .

, , , - static ?

0
1

Java. , :

import java.lang.reflect.Field;

public class test {
  public void method1() {
    System.out.println(getThisOrNull(new Object(){}));
  }

  public static void method2() {
    System.out.println(getThisOrNull(new Object(){}));
  }

  private static Object getThisOrNull(final Object o) {
    for (Field f: o.getClass().getDeclaredFields()) {
      if (f.getType().equals(test.class)) {
        try {
          return f.get(o);
        }
        catch (IllegalAccessException e) {
          // Omm nom nom...
        }
      }
    }
    return null;
  }

  public static void main(String[] args) {
    test t = new test();
    System.out.println(t);
    t.method1();
    t.method2();
  }
}

:

test@183f74d
test@183f74d
null

, , new Object(){}, , . .

, , :

java.lang.reflect.Modifiers.isStatic(new Object(){}.getClass().getEnclosingMethod().getModifiers())

this ( ), - . , Java, , . ( test.this). test.this, , , test.this , . , -. , , getThisOrNull .

, , , , , , , , , .

+3

Source: https://habr.com/ru/post/1546332/


All Articles