简体   繁体   English

基于java中的输入字符串名称返回对象

[英]Return object based on input string name in java

I have a requirement wherein I've to write a method which accepts "string" and based on this string i need to return an object of type MyObject. 我有一个要求,其中我要编写一个接受“字符串”的方法,并根据此字符串我需要返回一个MyObject类型的对象。 This can be done with using switch case, but how could this be achieved dynamically. 这可以通过使用开关盒来完成,但是如何动态地实现这一点。

In below case method can be called by giving "myObject1" as string, then this method should return myObject1 object. 在下面的case中,可以通过将“myObject1”作为字符串来调用,然后此方法应该返回myObject1对象。 How could this be done. 怎么可能这样做。

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 {

}

This can be done dynamically via reflection, but it would be highly impractical and unnecessary. 这可以通过反射动态完成,但这是非常不切实际和不必要的。 You should either use a switch or a Map to associate your string identifiers with your actual objects. 您应该使用switchMap将字符串标识符与实际对象相关联。

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);
}

我会考虑实施一个战略模式来做到这一点。

If you really want to do things like this reflection is your friend. 如果你真的想做这样的事情,反思就是你的朋友。 You can look up declared fields by name, and then use them to look up an instance variable. 您可以按名称查找声明的字段,然后使用它们查找实例变量。

I've modified your example to include a main method that looks up each instance of MyObject and also has a failure case. 我已修改您的示例以包含一个查找MyObject的每个实例的主方法,并且还有一个失败案例。 I've also modified MyObject so you can easily tell which instance has been found. 我还修改了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"));
    }

}

There is some useful information about reflection in the Oracle Java documentation . Oracle Java 文档中有关于反射的一些有用信息。

You can use: 您可以使用:

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

where className - the fully qualified name of the desired class see http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html for details 其中className - 所需类的完全限定名称,请参阅http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html以获取详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM