Home > Enterprise >  What is the need for Name interface in Java?
What is the need for Name interface in Java?

Time:02-24

In Java, when is the interface Name (which extends CharSequence) useful? Why not just use final String instead? I do not see any classes that implement Name.

Alternatively, what I am interested is the use cases of Name, CharSequence, and the String class.

CodePudding user response:

It is more than just a String.

In the description of the equals method it says:

Note that the identity of a Name is a function both of its content in terms of a sequence of characters as well as the implementation which created it.

So this implies that there is more to an object that implements Name than just its character representation. It also has to know about the implementation which created it.

If you want to just compare the content you have to use contentEquals.

But you are probably not going to be creating classes using this interface yourself. It is part of the Java language model.

CodePudding user response:

To summarize the answer based on the comments: By @Mark Rotteveel

This is part of the package java.lang.model.element which is "Interfaces used to model elements of the Java programming language.". In other words, it is not general purpose. And there are implementations, but just not in a public API as these interfaces are the API (e.g. in Temurin 11, there are
com.sun.tools.javac.util.Name,
com.sun.tools.javac.util.SharedNameTable.NameImpl and
com.sun.tools.javac.util.UnsharedNameTable.NameImpl).

And it is more than just a string based on @rghome answer.

Moreover, the reason the modeling is also provided in the same language is: By @Zabuzard

It is mostly for the meta-aspects that Java provides, in particular the reflection API that allows you to inspect the code and retrieve meta-information about it, or to dynamically trigger stuff. For example call a method by its name, given by user input.

CodePudding user response:

CharSequence is a very general interface, more so than String, and contrary to the obiquitous usage of String one could have used CharSequence instead, so one could pass a StringBuilder too.

However pro String (a class) counts its evident immutability and extra methods. Though the interface CharSequence itself does not have mutable functions too. As only StringBuilder and String are the most useful implementation, one may normally forget about using CharSequence.

Name is a dedicated interface for language modeling itself. It is a form of wrapping a value type (String here) in its own type for specific usage. Like wrapping a time String in a Time. Note that for a case-insensitive language the Name#equals could ignore the case (as in PascalName implements Name). The class/interface should not be used outside language modeling. In the model a Name may contain its declaration.

  • Related