The easiest way to do this would be to register all instances of Student
when you create them:
class Student {
private static final Map<String, Student> registry = new HashMap<>();
Student() {
registry.put(this.toString(), this);
}
static Student fromString(String address) {
return registry.get(address);
}
}
Then you could get the instance in your method using Student.fromString(address)
.
But there are a lot of reasons not to do this:
- It leaks memory, because Student instances can never be GC'd as they are reachable through the registry.
- It unsafely publishes the instance
- It means you can't change the value of
toString()
after the constructor, should you want to provide a custom implementation later
- It is mutable global state, which is never a good idea
- As a consequence of the previous point, it is hard to test
- Hash codes are not unique, so multiple instances of
Student
may have the same toString; in such a case, the implementation here would return the last-created instance with the given string.
as a few to get you started.
In short, it would be inadvisable to do this.
There are alternative ways to implement a registry which avoid some or all of these problems, but it would be reinventing the wheel.
You don't need to refer to instances by string: refer to them using references.