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?
, , , Java - , , .
Java getter setter . , - - IDE, . . . :
, , - . Python , Java . , Java, - string/object, . . , "" , . , , . (String, int, CustomObject ..), , Python.
, , . Variable. Dictionary : Variables. " ".
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() }; } }
Source: https://habr.com/ru/post/1585002/More articles:Download a zip file through ASP.NET MVC using DotNetZip - c #ASP MVC Download Zip Files - asp.net-mvc(C99) Expand a macro in another macro - cKeyword List Operators in Boost - c ++VS 2013 Community - Creating Code Snippets - c ++How to convert a MeshView to a CSG object using the JCSG library in JavaFX - javaIs there any connection between the clean clean () method and the clean () method? - pythonScikit Learn Algorithm has incorrect predictions, but is the ROC curve perfect? - pythonСтранное поведение String.length() - javaxslt 1.0 объединяет имена пустых элементов - xmlAll Articles