Kevuno
Kevuno

Reputation: 223

Call an object method with a variable name in java

I want to call a method "Talk" from the class Person. Lets say I have a lot of objects, for a lot of persons. So if I want to let the user enter the name of the person that he wants to call the method, how do I store the user input in a variable and then use it to call the method like this:

Scanner name= new Scanner(System.in);
String input= name.next();
input.Talk();

Insted of doing:

 switch (input) {
        case "John":  John.Talk();
                 break;
        case "Alex":  Alex.Talk();
                 break;
        case "Albert":  Albert.Talk();
                 break;
        ...
}

I hope I explained myself good enough. I think it is a simple concept therefore there must be a solution.

Upvotes: 1

Views: 960

Answers (3)

Pshemo
Pshemo

Reputation: 124275

You may want to use Map<String,Person>. In that map you put("Alex", AlexObject) and when user will write Alex you can simply get Person object stored in map with key Alex like

map.get(nameFromScanner).Talk()

But be careful since if map doesn't contain that name, get will return null so you will try to invoke Talk on null which will throw NullPointerException.

So you can try doing something like

Person p = map.get(nameFromScanner);
if (p != null){
    p.Talk();
}

Or since Java 8 we can use something like

Optional.ofNullable(map.get(nameFromScanner)).ifPresent(Person::Talk);

Upvotes: 6

Daniel Jipa
Daniel Jipa

Reputation: 888

You could use the factory design pattern for getting your objects.

Upvotes: 0

purring pigeon
purring pigeon

Reputation: 4209

I am not really sure what you are asking, but you could use an interface and a look up to find your correct Object at runtime.

Assuming your Persons are stored in a collection and can be found using a "predicate" you can use streams and filters to handle this:

Optional<Person> op = lst.stream().filter(person -> person.firstName.equals(input.getText())).findFirst();
if(op.isPresent()){
    op.get().talk();
}    

Upvotes: 0

Related Questions