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

64jmpszr  于 2021-07-13  发布在  Java
关注(0)|答案(4)|浏览(389)

我正在创建许多对象,称为: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,那么我必须重复大量代码,这会降低可读性,因为我必须用不同的对象调用相同的函数。

lnvxswe2

lnvxswe21#

实际答案是:一般来说,不应该在运行时使用字符串访问变量。这实际上是合适的例子很少,而且你的例子,简化了,虽然它可能是为了说明的目的,不是一个很好的匹配。
相反,为什么不简单地使用集合或数组来存储对象呢@t、 罗希思在他们的回答中举了一个例子。
不过,下面给出了您的问题的直接答案,因为它适用于java。虽然c#的代码不同,但c#中也提供了可用于此目的的语言特性,即反射。
如果 Obj1 , Obj2 如果在类中声明为静态或示例字段,则可以使用反射通过名称获取它们的值(请参阅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#。

nbewdwxp

nbewdwxp2#

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

mec1mxoz

mec1mxoz3#

代码如下:

//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();
}
syqv5f0l

syqv5f0l4#

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

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

相关问题