简体   繁体   English

您是否可以在Java中使用类似于关键字args的概念来最小化访问器方法的数量?

[英]Can you use a concept similar to keyword args for python in Java to minimize the number of accessor methods?

I recently learn that in Python 3, to minimize the number of accessor methods for a class, you can use a dictionaries to essentially just have one set of accessor methods as follows: 我最近了解到,在Python 3中,为了最小化类的访问器方法的数量,您可以使用词典基本上只有一组访问器方法,如下所示:

def __init__(self, **kwargs):
    self.properties = kwargs

def get_properties(self):
    return self.properties

def get_property(self, key):
    return self.properties.get(key, None)

This seems really useful and I want to apply something similar in Java. 这似乎非常有用,我想在Java中应用类似的东西。 I have been working on applications that may have multiple attributes, and creating and keeping track of all the accessor methods can be a pain. 我一直在研究可能具有多个属性的应用程序,并且创建和跟踪所有访问器方法可能很痛苦。 Is there a similar strategy that I could use for Java? 是否有类似的策略我可以用于Java?

Use that pattern if it suits and it fits best but it really should be an exception to the rule in Java - it will probably not be appropriate. 如果它适合并且它最适合使用该模式,但它确实应该是Java规则的一个例外 - 它可能不合适。

Best practice in Java is to use getter and setter methods for each variable. Java中的最佳实践是对每个变量使用getter和setter方法。 Yes it's more code - so what - if your lazy get your IDE to auto-generate them. 是的,这是更多的代码 - 所以 - 如果你的懒惰让你的IDE自动生成它们。 It's there for a very good reason. 这是有充分理由的。 Many good reasons. 很多好理由。 Some are; 有些是;

  • Promotes private variables 促进私有变量
  • Defines an external interface to other classes allowing the class to control what and how to set or get variables 定义其他类的外部接口,允许类控制设置或获取变量的内容和方式
  • Promotes good coding practice by establishing a standard way to deal with object variables 通过建立处理对象变量的标准方法来促进良好的编码实践

The problem you'll encounter here by porting this pattern over is due to typing. 通过移植此模式,您将遇到的问题是打字。 Python is dynamically typed and Java is statically typed. Python是动态类型的,Java是静态类型的。 So, in order to use the same pattern in Java, you will have to store the values in something like a string/object array and then return them like that as an object or as a String. 因此,为了在Java中使用相同的模式,您必须将值存储在类似字符串/对象数组的内容中,然后将它们作为对象或String返回。 then you'll have to convert them sometime later. 那么你以后必须转换它们。 Maybe if your 'properties' were all strings it would be okay. 也许如果你的'属性'都是字符串,那就没关系。 There are exceptions to the rule, but you need to know all of the rules in order to break them well. 该规则有例外,但您需要了解所有规则才能打破它们。 If they are different types (String, int, CustomObject etc.) don't use the same pattern you use in Python. 如果它们是不同的类型(String,int,CustomObject等),请不要使用在Python中使用的相同模式。

No there is no kwargs in java. 不,java中没有kwargs。 Instead you can something similar to your function by using java varargs to save them as java properties. 相反,您可以使用java varargs将它们保存为java属性,从而使您的函数类似。

You do you can something like this: 你可以做到这样的事情:

useKwargs("param1=value1","param2=value2");

Example code: 示例代码:

public void useKwargs(String... parameters) {

        Properties properties = new Properties();

        for (String param : parameters) {
            String[] pair = parseKeyValue(param);

            if (pair != null) {
                properties.setProperty(pair[0], pair[1]);
            }

        }

        doSomething(properties);
    }

    public void doSomething(Properties properties) {
        /**
         * Do something using using parameters specified in the properties
         */

    }

    private static String[] parseKeyValue(String token) {
        if (token == null || token.equals("")) {
            return null;
        }

        token = token.trim();

        int index = token.indexOf("=");

        if (index == -1) {
            return new String[] { token.trim(), "" };
        } else {
            return new String[] { token.substring(0, index).trim(),
                    token.substring(index + 1).trim() };
        }

    }

Im not sure if this is helpful to you, but Ill try to answer anyway. 我不确定这对你是否有帮助,但我还是试着回答。 I'd first make a class Variable. 我首先创建一个类Variable。 Then I'd make a class Dictionary with one lists:Variables. 然后我会创建一个带有一个列表的类Dictionary:Variables。 Then I'd make the function take a Dictionary as argument. 然后我让函数将Dictionary作为参数。

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

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