如何使用字符串输入访问现有对象(将字符串输入转换为对象名)



我正在创建许多对象,称为:Obj1,Obj2….ObjX

Object Obj1 = new Object();
Object Obj2 = new Object();
Object ObjX = new Object();

现在我有一个函数,我想访问其中一个对象。

public void useObject(int objectNumber) {
     String objectName = "Obj" + objectNumber;
     objectName.doAnythingWithThisObject();
     }

类似的东西在C#或Java中可能吗?我不想使用类似的东西

switch(objectNumber) {
      case 1: 
        Obj1.doThis();
       break;
      case 2: 
        Obj2.doThis();
       break;

如果我要使用switch/If-else,那么我必须重复很多代码,这些代码会降低这个东西的可读性,因为我必须用不同的对象调用相同的函数

实际的答案是:一般来说,您不应该在运行时使用字符串访问变量。这实际上是合适的情况很少,并且您的示例(尽管可能是为了说明目的而简化的)是而不是

相反,为什么不简单地使用集合或数组来存储对象呢@T.R.Rohith在他们的回答中举了一个例子。

尽管如此,下面给出了您的问题的直接答案,因为它适用于Java。虽然C#的代码会有所不同,但可以用于此目的的语言功能,即反射,在C#中也可用。


如果Obj1Obj2等被声明为类中的静态字段或实例字段,则可以使用反射通过它们的名称获取它们的值(请参阅Java的相关文档)。如果它们是方法的本地,那么没有简单的方法可以做到这一点(请参阅以下问题:对于Java,对于C#)。

静态字段

class Something {
    static Object obj1 = new Object();
    static Object obj2 = new Object();
    // etc.
}

(我可以自由地用小写字母开头字段名,因为这是Java中公认的做法。)

在这种情况下,您可以使用以下代码(您需要导入java.lang.reflect.Field)通过变量名称获取变量的值:

// Get field, named obj1, from class Something.
Field f = Something.class.getDeclaredField("obj1");
// This line allows you access the value of an inaccessible (non-public) field.
f.setAccessible(true);
// Assigning the value of the field, named obj1, to obj.
// You may want to cast to a more concrete type, if you know exactly what is stored in obj1.
// The parameter for get() is ignored for static fields, so simply pass null.
Object obj = f.get(null);
// Now you can do whatever you want with obj, 
// which refers to the same object as static field obj1 of Something.
System.out.println(obj);

实例字段

class Something {
    Object obj1 = new Object();
    Object obj2 = new Object();
    // etc.
}

对于实例字段,您可以用几乎完全相同的方式来执行此操作,只需要将类的一个实例传递给f.get()。因此,为了举例,让我们假设我们有一个类Something的实例,称为sth

// Let's say this is an instance of our class
Something sth = new Something();
// ...
// Get field, named obj1, from class Something.
Field f = Something.class.getDeclaredField("obj1");
// This line allows you access the value of an inaccessible (non-public) field.
f.setAccessible(true);
// Assigning the value of the field, named obj1, to obj.
// You may want to cast to a more concrete type, if you know exactly what is stored in obj1.
// The parameter for get() is the instance of Something, 
// for which you want to retrieve the value of an instance field, named obj1.
Object obj = f.get(sth);
// Now you can do whatever you want with obj,
// which refers to the same object as instance field obj1 of sth.
System.out.println(obj);

局部变量

在这种情况下,你可能运气不好。同样,请参阅以下链接:Java、C#。

这听起来像是一个经典的战略模式问题战略设计模式

以下是代码:

    //Declare this in the class so that it can be called by any method
static Object[] array = new Object[4];
public static void main()
{
    //Use this to initialize it
    Object[] array = new Object[4];
    for(int i=0;i<4;i++)
    {
        array[i] = new Object();
    }
    //You can now easily call it
    useObject(0);
    useObject(1);
    useObject(2);
    useObject(3);
}
//Your numbers may be off by 1 because we are using an array but that is easily adjusted
public static void useObject(int objectNumber)
{
    array[objectNumber].doAnythingWithThisObject();
}

答案是……不要。请改用数组。这正是他们的目的。

ObjectType[] objectArray = new ObjectType[10]; // Or as many as required.
for (int i = 0; i < objectArray.length; i++) {
    objectArray[i] = new ObjectType(); // Or whatever constructor you need.
}
// Then access an individual object like this...
ObjectType obj = objectArray[4];
// Or...
objectArray[5].someMethod();

相关内容

  • 没有找到相关文章

最新更新