Question

Is there any tricky way to use Java reserved words as variable, method, class, interface, package, or enum constant names?

Was it helpful?

Solution

No, there is no way. That's why they're labeled "reserved".

OTHER TIPS

This is a valid question. Such a thing is possible in other languages. In C#, prefix the identifier with @ (as asked before); in Delphi, prefix with &. But Java offers no such feature (partly because it doesn't really need to interact with identifiers defined by other languages the way the .Net world does).

Most often this issue comes up for "class", in this case it is customary to write "clazz".

Strictly speaking you can't, unless you get your hands on a buggy compiler implementation that doesn't adhere to the Java language spec.

But where there's a will, there's a way. Copy the following code into your IDE, switch the source file encoding to UTF-16 and here we go:

public class HelloWorld {

    public static void main(String[] args) {

        HelloWorld.nеw();
    }

    public static void nеw () {
        System.out.println("Hello,World");
    }

}

This code is a well-formed and valid Java class. However, as you have guessed there is a little trick: the 'е' character within "new" identifier does not belong to the ASCII character set, it is actually a cyrrilic 'е' (prounanced 'YE').

Current Java language spec explicitly permits, and this an important point to make, the use of Unicode for naming identifiers. That means that one has an ability to freely call her or his classes in French, Chinise or Russian if they wish. It is also possible to mix and match the alphabets within code. And historically, some letters within Latin and other alphabets are lookalikes.

As a result: no, you can't use the reserved words as identifiers, but you can use identifiers that look exactly like reserved words.

Whether anyone should be doing it is a totally different matter.

No, you can't do this. For more information please go to JLS Sections 3.8, 3.9

The following character sequences, formed from ASCII letters, are reserved for use as keywords and cannot be used as identifiers (§3.8):

Keyword: one of
        abstract    continue    for           new          switch
        assert      default     if            package      synchronized
        boolean     do          goto          private      this
        break       double      implements    protected    throw
        byte        else        import        public       throws
        case        enum        instanceof    return       transient
        catch       extends     int           short        try
        char        final       interface     static       void 
        class       finally     long          strictfp     volatile
        const       float       native        super        while

Yes, there is. You have to use reserved words from the future. Like what happened with different methods called assert() in pre-1.4 code.

Hope it helps!

Huh? Why would you want to do that? You can write them in l33t, that will fool the compiler.

class cl4ss {
  String r3turn() {
    return "but why?";
  }
}

I know it's old question still, might help someone.

It's possible by using GSON's Field Naming Support

eg.

@SerializedName("new")
private String New;
public String getNew ()
{
    return New;
}
public void setNew (String aNew)
{
    New = aNew;
}

It's bad enough some case-sensitive languages allow things like the following:

class New;

class Something
{
    New makeNew()
    {
      return new New();
    }
}

But why would you ever want to be able to write a line of code like this:

class new;

class Something
{
    bool if;

    new makeNew()
    {
        return if ? new new() : null;
    }
}

Just take a look at the syntax highlighting. Even it gets confused!

There is no way to use reserved words with the javac compiler.

Technically, you can edit the names inside the class file once it's compiled to be anything you want: at that stage, the VM doesn't care, because it's not dealing with source code any more. I believe some obfuscators use this technique.

PL/1 (a 1960's IBM mainframe programming language still around today) rather famously required that while some words act like keywords in certain contexts, all words can be used as identifiers. This isn't even that hard to do in a parser if you set out to be consistent about it. PL/1 was considered to a rather big langauge, and the langauge committee worried that many programmers wouldn't learn all of it, and then would get suprised when they tried to use the keyword from a part they didn't know as an identifier. So you could write things like:

IF BEGIN=ELSE THEN CALL=3 ELSE CALL FOO(ENDIF) ENDIF

As others have noted here, the ability to do this isn't a recommendation.

The Java designers decided the number of keywords in the langauge was modest, and reserved the set. They even reserved 'GOTO', which isn't actually allowed in any real Java program.

Not sure what you're trying to do, but $ is a valid character in identifiers, so you could do, say:

int $return = 5;

It looks a little weird, but it does work.

In Scala you can use backticks. For example: myVarialbe.`class`

If you really need to use a field/local variable/method named the same as a reserved word, I suggest appending an underscore at the end of the name:

// JPA entity mapping class:

private Boolean void_;

public Boolean getVoid_() { ... }
void setVoid_(Boolean void_) { ... }

It is a more readable choice (IMHO) than appending chars at the beginning of the name (fVoid, aVoid, vVoid, etc.)

The code above is a real world case that happened to me, working with a legacy database, in which the invoice table had a field named void indicating whether the document had been voided or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top