Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java name collision between variable and top-level package name

Triggered by this bug report AVRO-1814 I reduced the problem to this minimal example case in Java that simply shows the core of the effect.

package nl.basjes.experiment;

public class NamingClash {
  String nl = "foo";

  public void test() {
    nl.basjes.experiment.NamingClash.foo();
  }

  private static void foo() {
    // Do something
  }
}

Trying to compile this will give you

error: cannot find symbol
    nl.basjes.experiment.NamingClash.foo();
      ^
  symbol:   variable basjes
  location: variable nl of type String

In AVRO the code is generated and it must try to avoid name collisions under the assumption people will sometimes choose unexpected names.

So assume in this example that

  1. The fully qualified class name in the 'test()' method is needed to avoid a collision.
  2. The variable 'nl' is just the name used in the schema definition.
  3. Generating a field like _nl__ and have getters and setters would be a change that will break backwards compatibility because the nl field has always been public.

Other than telling people "Just don't do that".

Is there a solution to avoid these conflicts?


Note that for the AVRO bug that triggered this question I found a workaround. Here I'm looking for the 'generic answer'.

like image 517
Niels Basjes Avatar asked Mar 25 '16 15:03

Niels Basjes


1 Answers

I can see two solutions to the problem:

1) call the method using a method name qualified only by just the current class name, instead of a fully qualified name:

public void option1() {
    NamingClash.foo();
}

2) call the static method through the current class object's this pointer, and suppress the "static-access" warning.

@SuppressWarnings("static-access")
public void option2() {
    this.foo();
}
like image 66
AJNeufeld Avatar answered Oct 15 '22 15:10

AJNeufeld