-2

我想根据从字符串设置的值在 java 中设置一个键,对不起,我不能很好地解释这个,所以我用 php 写了这个,这是一个例子。

class Test() {

    public setField($key, $value) {
        $this->{$key} = $value;
    }
}

$class = new Test()
$class->setField("hello", "hello world");
echo $class->hello;
4

3 回答 3

2

地图接口给出了请求的行为:

import java.util.HashMap;

public class StackOverflow {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("hello", "hello world");
        System.out.println(map.get("hello"));
    }
}

但是您通常希望将变量用作键,然后您需要一种方法来设置和检索每个变量。

public class Test {
    private String hello;

    public void setHello(String hello) {
        this.hello = hello; 
    }

    public String getHello() {
        return hello;
    }
}
public class StackOverflow {
  public static void main(String[] args) {
    Test test = new Test();
    test.setHello("Hello world");
    System.out.println(test.getHello());
  }
}

或者您可以将变量公开:

   public class Test {
        public String hello;
    }
    public class StackOverflow {
      public static void main(String[] args) {
        Test test = new Test();
        test.hello = "Hello world";
        System.out.println(test.hello);
      }
    }
于 2013-06-28T01:20:37.877 回答
1

Java 没有像 PHP 这样的内置动态变量。实现相同功能的最简单方法是使用Map

public class Test {
    private Map<String, String> map = new HashMap<String, String>();

    public void setField(String key, String value) {
        map.put(key, value);
    }

    public String getField(String key) {
        return map.get(key);
    }
}

Test test = new Test();
test.setField("hello", "hello world");
System.out.println(test.getField("hello"));
于 2013-06-28T01:17:35.320 回答
0

您必须在 Java 中手动完成。类似于以下内容:

class Test(){
    private HashMap<Object, Object> inner_objects;

    public void setField(Object key, Object value) {
        this.inner_objects.put(key, value);
    }

    public Object getField(Object key){
        return this.inner_objects.get(key);
    }
}

当然,这个例子可以在几个方面进行改进,但这只是为了给你一个大致的想法。

但由于没有运算符重载,您不能将->工作作为getField,因此您需要getField(key)每次都调用。

于 2013-06-28T01:17:19.303 回答