有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java/从字符串到Java代码

我有一些从文件中以字符串格式获取的值

例如,在文件A中,我有:

id = 342
name = Jonatan
country = USA

此外,我还有一个类:person,其中包含以下字段:

String id;
String name;
String country;
String grades;
String location;

我有所有领域的getter和setter

现在,我想创建一个新的person实例,它代表Jonatan。 但是-我不想更新所有字段,只更新我需要的字段

因此,我要做的是下一步:从文件中获取详细信息,然后为每个do集合更新正确的值。例如,setName(Jonatan)。问题是我的name是字符串格式。所以我不能使用setName——因为名称是字符串格式的,Java不允许我选择调用字符串格式的方法

有简单的方法吗


共 (3) 个答案

  1. # 1 楼答案

    使用java反射,您可以确定哪些方法/字段可用

    您可以使用此示例将键/值对传递到doReflection方法中,以在Bean类的实例中设置属性的新值

    public class Bean {
    
        private String id = "abc";
    
        public void setId(String s) {
            id = s;
        }
    
        /**
         * Find a method with the given field-name (prepend it with "set") and
         * invoke it with the given new value.
         * 
         * @param b The object to set the new value onto
         * @param field  The name of the field (excluding "set")
         * @param newValue The new value
         */
        public static void doReflection(Bean b, String field, String newValue) throws NoSuchMethodException,
                SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
            Class<? extends Bean> c = b.getClass();
            Method id = c.getMethod("set" + field, String.class);
            id.invoke(b, newValue);
        }
    
        public static void main(String... args) throws NoSuchMethodException, SecurityException, IllegalArgumentException,
                InvocationTargetException, IllegalAccessException {
            Bean bean = new Bean();
            System.out.println("ID before: " + bean.id);
            doReflection(bean, "Id", "newValue");
            System.out.println("ID after: " + bean.id);
    
            // If you have a map of key/value pairs:
            Map<String, String> values = new HashMap<String, String>();
            for(Entry<String, String> entry : values.entrySet())
                doReflection(bean, entry.getKey(), entry.getValue());
        }
    
  2. # 2 楼答案

    我喜欢@michael_的答案加上BeanUtils。如果您想不使用,可以写:

    Person person = new Person();
    Properties properties = new Properties();
    properties.load(new FileInputStream("the.properties"));
    for (Object key : properties.keySet()) {
        String field = (String) key;
        String setter = "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
        Method method = Person.class.getMethod(setter, String.class);
        method.invoke(person, properties.get(key));
    }
    

    并不是说流在使用后应该关闭,而是这个简短的示例只适用于String属性

  3. # 3 楼答案

    你可以看看Apache BeanUtils

    该应用程序非常简单,可以调用个人调用的setId(“42”):

    PropertyUtils.setSimpleProperty(person, "id", "42");