简体   繁体   English

使用out反射调用动态java方法

[英]Invoke dynamic java method with out reflection

I have data type which contains 100 properties and 100 getter methods (getproperty1....getproperty100). 我有数据类型,包含100个属性和100个getter方法(getproperty1 .... getproperty100)。

I get an input from the user like 我从用户那里得到了一个输入

Property1
Property2
.
.
Property100

How can I invoke in a quick way the method in this logic 如何快速调用此逻辑中的方法

For property1 I need to invoke getproperty1
For propertyI I need to invoke getpropertyI

How can I do this with out using if else , or switch statement or reflection in an efficient way. 如何在不使用if elseswitch语句或反射的情况下以高效的方式执行此操作。

Thanks 谢谢

Your best bet is probably going to be an array or hashmap of some type, and access it by index/key: 您最好的选择可能是某种类型的数组或散列映射,并通过索引/键访问它:

public class DataType {
    private Map<String, DataProperty> data = new HashMap<String, DataProperty>();

    public DataProperty getProperty(String key) {
        return data.get(key);
    }

    public void setProperty(String key, DataProperty value) {
        data.put(key, value);
    }
}

Although, 100 properties seems like a lot... see if you should break it up or otherwise re-organize it. 虽然,100个属性似乎很多...看看你是否应该分解或重新组织它。

1. If you need to invoke multiple methods I would suggest using the Strategy design pattern. 1.如果您需要调用多种方法,我建议您使用Strategy设计模式。 In it's simplest form you could try 在它最简单的形式你可以尝试

public interface Command<T> {
    public T getProperty();
}

and then create as many implementations as necessary. 然后根据需要创建尽可能多的实现。

2. If you are only interested in the return type and not the actual invokation the Map<String, T> would be a better alternative. 2.如果您只对返回类型而不是实际调用感兴趣,那么Map<String, T>将是更好的选择。

3. If you want to pass around the information in your program a good alternative would be to use the enum approach 3.如果你想传递你的程序中的信息,一个很好的选择是使用enum方法

public enum Command {
   Property1("some value"),
   Property2("some other value");

   private String str;
   public Command(String str) {
       this.str = str;
   }

   public String getVal() {
       return str;
   }
}

Which can be used like 哪个可以用

Command cmd = ...
String value = cmd.getVal();

You could refactor the class to be a Map. 您可以将该类重构为Map。 If you have a large number of objects like that it seems more along the lines of a map than an object. 如果你有大量的对象,它看起来更像是一个地图的线而不是一个对象。

Map<String, Object>

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

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