Is it possible to make JavaScript style settings in Java?
Sometimes I just need to define a lot of settings for some class, it's just hard to define 5 or more properties in constructor, because you don't really know what property you are setting. In JavaScript you can use name for settings with JSON style. Is somet开发者_JS百科hing similar possible in Java? Or are there any suggestion how I should define large amount of details inside code (and I mean only inside code needed attributes, so xml is not possible here).
$.plugin.defaults = {
css: {
padding: 0,
margin: 0,
textAlign: 'center',
color: '#000',
border: '0px none'
}
}
Try the builder pattern. This blog also has some nice insight. And of course, there are several other questions on SO that have "try the builder pattern" as the answer, so a little searching here would go along way.
Also...well, just use one of the several JSON-to-Java libraries. Just started with GSON myself, seems to work nicely.
You cannot name parameters directly in method calls in Java. However, you can approximate it with the named-parameter idiom.
I'll suggest a different approach: if the styles aren't programmatically generated - that is, these are just literal strings in your Java code - why not put them straight into your CSS file?
E.g.
.foo {
padding: 0;
margin: 0;
text-align: center;
color: #000;
border: 0;
}
Then, all you have to do is add the classname foo
to the element you're interested in.
精彩评论