Can you use a concept similar to the args keywords for python in Java to minimize the number of access methods?

I recently learned that in Python 3, to minimize the number of accessor methods for a class, you can use dictionaries to essentially have only one set of accessor methods:

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 like this in Java. I am working on applications that can have multiple attributes, and creating and tracking all access methods can be painful. Is there a similar strategy that I could use for Java?

+4
source share
3 answers

, , , Java - , , .

​​Java getter setter . , - - IDE, . . . :

  • , ,
  • , .

, , - . Python , Java . , Java, - string/object, . . , "" , . , , . (String, int, CustomObject ..), , Python.

+2

, , . Variable. Dictionary : Variables. " ".

0

There are no quarts in java. Instead, you can do something similar to your function using java varargs to save them as java properties.

You can do something like this:

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

Code example:

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

    }
0
source

Source: https://habr.com/ru/post/1585002/


All Articles