Is there a standard Java interface with a getName() method that returns a string? I keep finding I have to make my own:
/** objects which know their own names,
* e.g. that are indexed in a Map by their name
*/
interface NamedObject
{
public String getName()
}
but I’d much rather use a standard one if it’s out there.
edit for an example — which I think is somewhat of a red herring to my question, so I specifically do not want answers suggesting alternatives that are specific to the following situation. (I’ve run into the need for a NamedObject interface several times, so I was hoping it was something in a standard library.)
But since you asked for some background context, here it is:
@Override public void stateChanged(ChangeEvent e) {
Object obj = e.getSource();
if (obj instanceof NamedObject)
{
String name = ((NamedObject)obj).getName();
/* do something based on object's name */
}
}
In my current project, I have a system with three elements: a source, a transmission method, and a receiver. I want to get some information from the source to a receiver, and I control the implementation of both. The transmission method unfortunately is stuck using an object that supports ChangeListener, so all the receiver gets a ChangeEvent with which I can get a source object.
So I have to use implied shared semantics between my source and receiver, i.e. there’s a shared understanding that the source object passed in the ChangeEvent is of class X, where I can pick class X. In this case, all I really care about is the name, from which I can get additional data. I can define my own interface, I was just hoping to be able to use a standard interface since the source and receiver are in different .jar files…
As far as I know, not in the Java SE API.
It is debatable whether a generic
NamedObjectinterface makes sense. Consider for example aPersonclass and aUnixNamedPipeclass. Both could share the sameNamedObjectinterface, but their names actually have vastly different semantics. I can’t see for example a case where it would make sense to have aCollection<NamedObject>with bothPersons andUnixNamedPipes.It would make sense to define such an interface if you have
PetCat,PetDogand maybePetRockclasses. But then you will probably have aPetsuper class that already definesgetName()for all pets. In this case, what the concept of what a “name” is will not change from one pet to another.