Return object based on input string name in java

I have a requirement in which I have to write a method that accepts a "string" and based on this string I need to return an object of type MyObject. This can be done using the switch enclosure, but how can this be achieved dynamically.

In the following case, the method can be called by specifying "myObject1" as a string, then this method should return the object myObject1. How can I do that.

public class HelloWorld {

    MyObject myObject1 = new MyObject();
    MyObject myObject2 = new MyObject();
    MyObject myObject3 = new MyObject();


public MyObject getMyObject(String string)
{
    return <<myObject1 or 2 or 3 based on string parameter name>>;
}

}


class MyObject {

}
+4
source share
4 answers

If you really want to do things like this reflection, your friend. You can search for declared fields by name, and then use them to search for an instance variable.

, , MyObject, . MyObject, , .

import java.lang.reflect.Field;

public class Reflection {

    MyObject myObject1 = new MyObject("1");
    MyObject myObject2 = new MyObject("2");
    MyObject myObject3 = new MyObject("3");

    public MyObject getMyObject(final String string) {
        try {
            final Field declaredField = this.getClass()
                    .getDeclaredField(string);
            final Object o = declaredField.get(this);
            if (o instanceof MyObject) {
                return (MyObject) o;
            }

        } catch (final Exception e) {
        }
        return null;
    }

    class MyObject {
        final String name;

        public MyObject(final String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            // TODO Auto-generated method stub
            return name;
        }

    }

    public static void main(final String[] args) {
        final Reflection r = new Reflection();
        System.out.println(r.getMyObject("myObject1"));
        System.out.println(r.getMyObject("myObject2"));
        System.out.println(r.getMyObject("myObject3"));
        System.out.println(r.getMyObject("invalid"));
    }

}

Oracle Oracle .

+1

, . switch, Map, .

Map<String, MyObject> identifiers = new HashMap<>();

...
identifiers.put("myObject1", myObject1);
identifiers.put("myObject2", myObject2);
identifiers.put("myObject3", myObject3);
...

public MyObject getMyObject(String string) {
    return identifiers.get(string);
}
+1

.

+1

:

Class<?> clazz = Class.forName(className);
Object object = clazz.newInstance();

className - . http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

0

Source: https://habr.com/ru/post/1530633/


All Articles