Question

I need to declare a method like so :

public void doSomething(Class class) {
...
}

and, of course, the class parameter name is not valid as it is a reserved keyword. However, in C# I can dodge that using the @ character as a prefix. Using the @ not only that I can 'solve' it but upon compilation, at the 'bytecode' (IL) level the name will be stripped of the @ character.

Anything similar in Java? All I found was _ and $. The dollar sign is the ugliest of them all, IMHO.


Later edit : I knew about the clazz thingie but I didn't mention it, hoping for something nicer. If that's the best, so be it. Is however some table of correspondence for all the reserved keywords? Something along the lines of :

class -> klass, clazz

switch -> swytch, svvitch ...


Later edit 2 : It's amazing how many snarky comments and useless input can a legitimate, IMHO, question can generate. I almost regret asking it.


Later edit 3 : It seems that in the Java world the best thing to do is to shut up and don't ask anything. Don't bother anyone and, even when noone asked/answered a certain question, keep quiet and don't talk.

Était-ce utile?

La solution

No. There is no way. Keywords are reserved and cannot be used. Escaping with some strange prefix (like in C#) is in my opinion no proper solution as this makes the code just uglier and less readable.

You can use type or clazz in your special case.

Autres conseils

The de facto standard is Class clazz. You'll see it in many APIs.

A common convention is to misspell the parameter name. In your case you would call the parameter clazz:

public void doSomething(Class clazz) {
...
}

I know it's ugly but it is the solution adopted by the Java community.

You cannot use the keywords as parameter name or variable name in java (same sensitive).

There are couple of alternatives:

  • Change the case of the parameter. Java is case sensitive, so it will not treat the parameter as a reserved word.
  • Use different name which sounds same as reserved word.

Your solution is clazz. It is more readable.

public void doSomething(Class clazz) {
 ...
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top