Related
I'm using listeners provided by Pircbotx (https://github.com/pircbotx/pircbotx/wiki/Documentation) to detect when a command is found in Twitch chat, and I am trying to use a different method depending on which Command is called (format is !command). Classes used: Listeners, Command.
Commands are stored in an array of Command objects, comprised of one String (name). Each Command object will ultimately use its own method that will be defined in the Command class. The Listeners object when instantiated will immediately place every element of the array into a hash table (commands).
When Listeners detects a message, it is stored using a local String variable (msg). When this happens, a loop iterates through the Command object array, and then.... is supposed to call the method that corresponds to that particular object, in this case Command.addDeath(). That's where I'm stuck.
I was previously using a bunch of if statements for my listeners, but when there's a bunch of commands things will get really, really messy. Apologies in advance if the formatting in my code block is weird, I'm pretty new to utilizing Stackverflow, and I'm also a Java novice that's learning as I go along. After looking at the code again, it would appear I don't really need the hash table - but I'm leaving it in there just in case you guys have any better ideas for what to do with them.
public class Listeners {
String name;
String message;
private static MessageEvent event;
Command [] commandNames = {new Command("!clearchat", new Command("!addDeath")};
Hashtable<String, Command> commands = new Hashtable<String, Command>();
public Listeners() {
for (int i = 0; i < commandNames.length; i++) {
commands.put(commandNames[i].name, new Command(commandNames[i].name));
}
if (event.getMessage() != null) {
String msg = event.getMessage();
for (int x = 0; x < commandNames.length; x++ ) {
if (msg.startsWith(commandNames[x].name)) {
// call Command method here
}
}
}
}
And here is the Command class:
public class Command {
String name;
public Command(String name) {
this.name = name;
}
public static void addDeath() {
DeathCounter.addDeath();
Listeners.sendMessage("Death Counter: " + DeathCounter.getDeaths());
}
}
You can use an interface for your commands:
public interface Command {
public abstract void execute();
}
Then have your commands implement the interface:
public class DeathCommand implements Command {
#Override
public void execute() {
DeathCounter.addDeath();
Listeners.sendMessage("Death Counter: " + DeathCounter.getDeaths());
}
}
In your listener class, map the command strings to instances of the corresponding command:
public class Listeners {
String name;
String message;
private static MessageEvent event;
static Map<String, Command> commands = new HashMap<>();
static {
commands.put("!addDeath", new DeathCommand());
}
public Listeners() {
if (event.getMessage() != null) {
String msg = event.getMessage();
Optional<String> key = commands.keySet().stream().filter(k -> msg.startsWith(k)).findFirst();
key.ifPresent(s -> commands.get(s).execute());
}
}
}
I replaced your Hashtable with a HashMap which is better in most ways (but is used the same way).
I'm a bit skeptical about having the map as a static member, but since I'm not familiar with your use case I leave that bit as is.
Edit
All Java classes have a default constructor (with no parameters) unless you write your own constructor (you have to write the default one yourself if you still want it). Interfaces don't have constructors since they can't be instantiated directly. They just specify methods that implementing classes must have. This allows you to have references (named fields/variables) of the interface type and be able to call the methods without knowing, or having to know, which implementation it is.
Example:
Command com = new DeathCommand();
com.execute(); // <- this will run the execute() code in the DeathCommand class
Command com2 = new SomeOtherCommand();
com2.execute(); // <- this will run the execute() code in the SomeOtherCommand class
The above code for Command is complete. There is nothing more. As for DeathCommand, and other implementations, you'll need to add what code is needed.
Each class and interface goes in it's own file named as the type:
Command.java
DeathCommand.java
Regarding HashTable vs HashMap. I should have said that it's better to use Map and it's implementations. If you need thread safety, use ConcurrentHashMap as agilob pointed out since regular HashMap is not thread safe.
Are there any practical uses of anonymous code blocks in Java?
public static void main(String[] args) {
// in
{
// out
}
}
Please note that this is not about named blocks, i.e.
name: {
if ( /* something */ )
break name;
}
.
They restrict variable scope.
public void foo()
{
{
int i = 10;
}
System.out.println(i); // Won't compile.
}
In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.
#David Seiler's answer is right, but I would contend that code blocks are very useful and should be used frequently and don't necessarily indicate the need to factor out into a method. I find they are particularly useful for constructing Swing Component trees, e.g:
JPanel mainPanel = new JPanel(new BorderLayout());
{
JLabel centerLabel = new JLabel();
centerLabel.setText("Hello World");
mainPanel.add(centerLabel, BorderLayout.CENTER);
}
{
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0,0));
{
JLabel label1 = new JLabel();
label1.setText("Hello");
southPanel.add(label1);
}
{
JLabel label2 = new JLabel();
label2.setText("World");
southPanel.add(label2);
}
mainPanel.add(southPanel, BorderLayout.SOUTH);
}
Not only do the code blocks limit the scope of variables as tightly as possible (which is always good, especially when dealing with mutable state and non-final variables), but they also illustrate the component hierarchy much in the way as XML / HTML making the code easier to read, write and maintain.
My issue with factoring out each component instantiation into a method is that
The method will only be used once yet exposed to a wider audience, even if it is a private instance method.
It's harder to read, imagining a deeper more complex component tree, you'd have to drill down to find the code you're interested, and then loose visual context.
In this Swing example, I find that when complexity really does grow beyond manageability it indicates that it's time to factor out a branch of the tree into a new class rather than a bunch of small methods.
It's usually best to make the scope of local variables as small as possible. Anonymous code blocks can help with this.
I find this especially useful with switch statements. Consider the following example, without anonymous code blocks:
public String manipulate(Mode mode) {
switch(mode) {
case FOO:
String result = foo();
tweak(result);
return result;
case BAR:
String result = bar(); // Compiler error
twiddle(result);
return result;
case BAZ:
String rsult = bar(); // Whoops, typo!
twang(result); // No compiler error
return result;
}
}
And with anonymous code blocks:
public String manipulate(Mode mode) {
switch(mode) {
case FOO: {
String result = foo();
tweak(result);
return result;
}
case BAR: {
String result = bar(); // No compiler error
twiddle(result);
return result;
}
case BAZ: {
String rsult = bar(); // Whoops, typo!
twang(result); // Compiler error
return result;
}
}
}
I consider the second version to be cleaner and easier to read. And, it reduces the scope of variables declared within the switch to the case to which they were declared, which in my experience is what you want 99% of the time anyways.
Be warned however, it does not change the behavior for case fall-through - you'll still need to remember to include a break or return to prevent it!
I think you and/or the other answers are confusing two distinct syntactic constructs; namely Instance Initializers and Blocks. (And by the way, a "named block" is really a Labeled Statement, where the Statement happens to be a Block.)
An Instance Initializer is used at the syntactic level of a class member; e.g.
public class Test {
final int foo;
{
// Some complicated initialization sequence; e.g.
int tmp;
if (...) {
...
tmp = ...
} else {
...
tmp = ...
}
foo = tmp;
}
}
The Initializer construct is most commonly used with anonymous classes as per #dfa's example. Another use-case is for doing complicated initialization of 'final' attributes; e.g. see the example above. (However, it is more common to do this using a regular constructor. The pattern above is more commonly used with Static Initializers.)
The other construct is an ordinary block and appears within a code block such as method; e.g.
public void test() {
int i = 1;
{
int j = 2;
...
}
{
int j = 3;
...
}
}
Blocks are most commonly used as part of control statements to group a sequence of statements. But when you use them above, they (just) allow you to restrict the visibility of declarations; e.g. j in the above.
This usually indicates that you need to refactor your code, but it is not always clear cut. For example, you sometimes see this sort of thing in interpreters coded in Java. The statements in the switch arms could be factored into separate methods, but this may result in a significant performance hit for the "inner loop" of an interpreter; e.g.
switch (op) {
case OP1: {
int tmp = ...;
// do something
break;
}
case OP2: {
int tmp = ...;
// do something else
break;
}
...
};
You may use it as constructor for anonymous inner classes.
Like this:
This way you can initialize your object, since the free block is executed during the object construction.
It is not restricted to anonymous inner classes, it applies to regular classes too.
public class SomeClass {
public List data;{
data = new ArrayList();
data.add(1);
data.add(1);
data.add(1);
}
}
Anonymous blocks are useful for limiting the scope of a variable as well as for double brace initialization.
Compare
Set<String> validCodes = new HashSet<String>();
validCodes.add("XZ13s");
validCodes.add("AB21/X");
validCodes.add("YYLEX");
validCodes.add("AR2D");
with
Set<String> validCodes = new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR5E");
}};
Instance initializer block:
class Test {
// this line of code is executed whenever a new instance of Test is created
{ System.out.println("Instance created!"); }
public static void main() {
new Test(); // prints "Instance created!"
new Test(); // prints "Instance created!"
}
}
Anonymous initializer block:
class Test {
class Main {
public void method() {
System.out.println("Test method");
}
}
public static void main(String[] args) {
new Test().new Main() {
{
method(); // prints "Test method"
}
};
{
//=========================================================================
// which means you can even create a List using double brace
List<String> list = new ArrayList<>() {
{
add("el1");
add("el2");
}
};
System.out.println(list); // prints [el1, el2]
}
{
//==========================================================================
// you can even create your own methods for your anonymous class and use them
List<String> list = new ArrayList<String>() {
private void myCustomMethod(String s1, String s2) {
add(s1);
add(s2);
}
{
myCustomMethod("el3", "el4");
}
};
System.out.println(list); // prints [el3, el4]
}
}
}
Variable scope restrict:
class Test {
public static void main() {
{ int i = 20; }
System.out.println(i); // error
}
}
You can use a block to initialize a final variable from the parent scope. This a nice way to limit the scope of some variables only used to initialize the single variable.
public void test(final int x) {
final ClassA a;
final ClassB b;
{
final ClassC parmC = getC(x);
a = parmC.getA();
b = parmC.getB();
}
//... a and b are initialized
}
In general it's preferable to move the block into a method, but this syntax can be nice for one-off cases when multiple variables need to be returned and you don't want to create a wrapper class.
I use the anonymous blocks for all the reasons explained in other answers, which boils down to limiting the scope of variables. I also use them to have proper delimitation of pairs of method belonging together.
Consider the following excerpt:
jg.writeStartObject();
{
jg.writeStringField("fieldName", ((JsonFormFieldDependencyData.FieldLocator) valueOrLocator).getFieldName());
jg.writeStringField("kind", "field");
}
jg.writeEndObject();
Not only you can see at a glance that the methods are properly paired, but doesn't also kind of look like the output too ?
Just be careful to not abuse it and end up in-lining methods ^^
Refer to
Are fields initialized before constructor code is run in Java?
for the order or execution used in this discussion.
Instance init blocks in Java solve initialization problems other languages have been grappling with - what if we need to enforce of perform an instance initialization that must be run but only after all the static intializers and constructors have completed.
Consider this issue is more prevalent in C# with WPF components where sequence of component initialization is tighter. In Java backend such issues are probably resolved by some redesign. So this remains an overly simplistic illustration of the issue.
public class SessionInfo {
public String uri;
..blah, blah ..
}
abstract public class Session {
final public SessionInfo sessInf;
final public Connection connection;
public Session(SessionInfo sessInf) {
this.sessInf = sessInf;
this.connection = connect(sessInf.uri);
}
abstract void connect(String uri) throws NullPointerException;
}
sessInf.uri is looked up by each impl by the impl constructor.
abstract public class SessionImpl extends Session {
public SessionImpl (SessionInfo sessInf) {
super(sessInf);
sessInf.uri = lookUpUri();
}
..blah, blah ..
}
If you trace the flow, you will find that SessionImpl connect would throw NPE, simply because
SessionImpl constructor is run after constructor of parent Session.
therefore sessInf.uri will be null
and connect(sessInf.uri) at parent constructor would hit NPE.
The solution for such requirement for such a right initialization cycle is
abstract public class Session {
final public SessionInfo sessInf;
final public Connection connection;
public Session(SessionInfo sessInf) {
this.sessInf = sessInf;
}
abstract void connect(String uri) throws NullPointerException;
// This block runs after all the constuctors and static members have completed
{
// instance init blocks can initialize final instance objects.
this.connection = connect(sessInf.uri);
}
}
In this way, you will be able to enforce getting connection onto all extension classes and have it done after all constructors have completed.
Describe a task, either with a comment or inherently due to the structure of your code and the identifiers chosen, and then use code blocks to create a hierarchical relationship there where the language itself doesn't enforce one. For example:
public void sendAdminMessage(String msg) throws IOException {
MessageService service; {
String senderKey = properties.get("admin-message-server");
service = MessageService.of(senderKey);
if (!ms.available()) {
throw new MessageServiceException("Not available: " + senderKey);
}
}
/* workaround for issue 1298: Stop sending passwords. */ {
final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
Matcher m = p.matcher(msg);
if (m.matches()) msg = m.group(1) + m.group(2);
}
...
}
The above is just some sample code to explain the concept. The first block is 'documented' by what is immediately preceding it: That block serves to initialize the service variable. The second block is documented by a comment. In both cases, the block provide 'scope' for the comment/variable declaration: They explain where that particular process ends. It's an alternative to this much more common style:
public void sendAdminMessage(String msg) throws IOException {
// START: initialize service
String senderKey = properties.get("admin-message-server");
MessageService service = MessageService.of(senderKey);
if (!ms.available()) {
throw new MessageServiceException("Not available: " + senderKey);
}
// END: initialize service
// START: workaround for issue 1298: Stop sending passwords.
final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
Matcher m = p.matcher(msg);
if (m.matches()) msg = m.group(1) + m.group(2);
// END: workaround for issue 1298: Stop sending passwords.
...
}
The blocks are better, though: They let you use your editor tooling to navigate more efficiently ('go to end of block'), they scope the local variables used within the block so that they cannot escape, and most of all, they align the concept of containment: You are already familiar, as java programmer, with the concept of containment: for blocks, if blocks, method blocks: They are all expressions of hierarchy in code flow. Containment for code for documentary reasons instead of technical is still containment. Why use a different mechanism? Consistency is useful. Less mental load.
NB: Most likely the best design is to isolate the initialisation of the MessageService object to a separate method. However, this does lead to spaghettification: At some point isolating a simple and easily understood task to a method makes it harder to reason about method structure: By isolating it, you've turned the job of initializing the messageservice into a black box (at least, until you look at the helper method), and to fully read the code in order of how it flows, you need to hop around all over your source files. That's usually the better choice (the alternative is very long methods that are hard to test, or reuse parts of), but there are times when it's not. For example, if your block contains references to a significant number of local variables: If you make a helper method you'd have to pass all those variables. A method is also not control flow and local variable transparent (a helper method cannot break out of the loop from the main method, and a helper method cannot see or modify the local variables from the main method). Sometimes that's an impediment.
Are there any practical uses of anonymous code blocks in Java?
public static void main(String[] args) {
// in
{
// out
}
}
Please note that this is not about named blocks, i.e.
name: {
if ( /* something */ )
break name;
}
.
They restrict variable scope.
public void foo()
{
{
int i = 10;
}
System.out.println(i); // Won't compile.
}
In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.
#David Seiler's answer is right, but I would contend that code blocks are very useful and should be used frequently and don't necessarily indicate the need to factor out into a method. I find they are particularly useful for constructing Swing Component trees, e.g:
JPanel mainPanel = new JPanel(new BorderLayout());
{
JLabel centerLabel = new JLabel();
centerLabel.setText("Hello World");
mainPanel.add(centerLabel, BorderLayout.CENTER);
}
{
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0,0));
{
JLabel label1 = new JLabel();
label1.setText("Hello");
southPanel.add(label1);
}
{
JLabel label2 = new JLabel();
label2.setText("World");
southPanel.add(label2);
}
mainPanel.add(southPanel, BorderLayout.SOUTH);
}
Not only do the code blocks limit the scope of variables as tightly as possible (which is always good, especially when dealing with mutable state and non-final variables), but they also illustrate the component hierarchy much in the way as XML / HTML making the code easier to read, write and maintain.
My issue with factoring out each component instantiation into a method is that
The method will only be used once yet exposed to a wider audience, even if it is a private instance method.
It's harder to read, imagining a deeper more complex component tree, you'd have to drill down to find the code you're interested, and then loose visual context.
In this Swing example, I find that when complexity really does grow beyond manageability it indicates that it's time to factor out a branch of the tree into a new class rather than a bunch of small methods.
It's usually best to make the scope of local variables as small as possible. Anonymous code blocks can help with this.
I find this especially useful with switch statements. Consider the following example, without anonymous code blocks:
public String manipulate(Mode mode) {
switch(mode) {
case FOO:
String result = foo();
tweak(result);
return result;
case BAR:
String result = bar(); // Compiler error
twiddle(result);
return result;
case BAZ:
String rsult = bar(); // Whoops, typo!
twang(result); // No compiler error
return result;
}
}
And with anonymous code blocks:
public String manipulate(Mode mode) {
switch(mode) {
case FOO: {
String result = foo();
tweak(result);
return result;
}
case BAR: {
String result = bar(); // No compiler error
twiddle(result);
return result;
}
case BAZ: {
String rsult = bar(); // Whoops, typo!
twang(result); // Compiler error
return result;
}
}
}
I consider the second version to be cleaner and easier to read. And, it reduces the scope of variables declared within the switch to the case to which they were declared, which in my experience is what you want 99% of the time anyways.
Be warned however, it does not change the behavior for case fall-through - you'll still need to remember to include a break or return to prevent it!
I think you and/or the other answers are confusing two distinct syntactic constructs; namely Instance Initializers and Blocks. (And by the way, a "named block" is really a Labeled Statement, where the Statement happens to be a Block.)
An Instance Initializer is used at the syntactic level of a class member; e.g.
public class Test {
final int foo;
{
// Some complicated initialization sequence; e.g.
int tmp;
if (...) {
...
tmp = ...
} else {
...
tmp = ...
}
foo = tmp;
}
}
The Initializer construct is most commonly used with anonymous classes as per #dfa's example. Another use-case is for doing complicated initialization of 'final' attributes; e.g. see the example above. (However, it is more common to do this using a regular constructor. The pattern above is more commonly used with Static Initializers.)
The other construct is an ordinary block and appears within a code block such as method; e.g.
public void test() {
int i = 1;
{
int j = 2;
...
}
{
int j = 3;
...
}
}
Blocks are most commonly used as part of control statements to group a sequence of statements. But when you use them above, they (just) allow you to restrict the visibility of declarations; e.g. j in the above.
This usually indicates that you need to refactor your code, but it is not always clear cut. For example, you sometimes see this sort of thing in interpreters coded in Java. The statements in the switch arms could be factored into separate methods, but this may result in a significant performance hit for the "inner loop" of an interpreter; e.g.
switch (op) {
case OP1: {
int tmp = ...;
// do something
break;
}
case OP2: {
int tmp = ...;
// do something else
break;
}
...
};
You may use it as constructor for anonymous inner classes.
Like this:
This way you can initialize your object, since the free block is executed during the object construction.
It is not restricted to anonymous inner classes, it applies to regular classes too.
public class SomeClass {
public List data;{
data = new ArrayList();
data.add(1);
data.add(1);
data.add(1);
}
}
Anonymous blocks are useful for limiting the scope of a variable as well as for double brace initialization.
Compare
Set<String> validCodes = new HashSet<String>();
validCodes.add("XZ13s");
validCodes.add("AB21/X");
validCodes.add("YYLEX");
validCodes.add("AR2D");
with
Set<String> validCodes = new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR5E");
}};
Instance initializer block:
class Test {
// this line of code is executed whenever a new instance of Test is created
{ System.out.println("Instance created!"); }
public static void main() {
new Test(); // prints "Instance created!"
new Test(); // prints "Instance created!"
}
}
Anonymous initializer block:
class Test {
class Main {
public void method() {
System.out.println("Test method");
}
}
public static void main(String[] args) {
new Test().new Main() {
{
method(); // prints "Test method"
}
};
{
//=========================================================================
// which means you can even create a List using double brace
List<String> list = new ArrayList<>() {
{
add("el1");
add("el2");
}
};
System.out.println(list); // prints [el1, el2]
}
{
//==========================================================================
// you can even create your own methods for your anonymous class and use them
List<String> list = new ArrayList<String>() {
private void myCustomMethod(String s1, String s2) {
add(s1);
add(s2);
}
{
myCustomMethod("el3", "el4");
}
};
System.out.println(list); // prints [el3, el4]
}
}
}
Variable scope restrict:
class Test {
public static void main() {
{ int i = 20; }
System.out.println(i); // error
}
}
You can use a block to initialize a final variable from the parent scope. This a nice way to limit the scope of some variables only used to initialize the single variable.
public void test(final int x) {
final ClassA a;
final ClassB b;
{
final ClassC parmC = getC(x);
a = parmC.getA();
b = parmC.getB();
}
//... a and b are initialized
}
In general it's preferable to move the block into a method, but this syntax can be nice for one-off cases when multiple variables need to be returned and you don't want to create a wrapper class.
I use the anonymous blocks for all the reasons explained in other answers, which boils down to limiting the scope of variables. I also use them to have proper delimitation of pairs of method belonging together.
Consider the following excerpt:
jg.writeStartObject();
{
jg.writeStringField("fieldName", ((JsonFormFieldDependencyData.FieldLocator) valueOrLocator).getFieldName());
jg.writeStringField("kind", "field");
}
jg.writeEndObject();
Not only you can see at a glance that the methods are properly paired, but doesn't also kind of look like the output too ?
Just be careful to not abuse it and end up in-lining methods ^^
Refer to
Are fields initialized before constructor code is run in Java?
for the order or execution used in this discussion.
Instance init blocks in Java solve initialization problems other languages have been grappling with - what if we need to enforce of perform an instance initialization that must be run but only after all the static intializers and constructors have completed.
Consider this issue is more prevalent in C# with WPF components where sequence of component initialization is tighter. In Java backend such issues are probably resolved by some redesign. So this remains an overly simplistic illustration of the issue.
public class SessionInfo {
public String uri;
..blah, blah ..
}
abstract public class Session {
final public SessionInfo sessInf;
final public Connection connection;
public Session(SessionInfo sessInf) {
this.sessInf = sessInf;
this.connection = connect(sessInf.uri);
}
abstract void connect(String uri) throws NullPointerException;
}
sessInf.uri is looked up by each impl by the impl constructor.
abstract public class SessionImpl extends Session {
public SessionImpl (SessionInfo sessInf) {
super(sessInf);
sessInf.uri = lookUpUri();
}
..blah, blah ..
}
If you trace the flow, you will find that SessionImpl connect would throw NPE, simply because
SessionImpl constructor is run after constructor of parent Session.
therefore sessInf.uri will be null
and connect(sessInf.uri) at parent constructor would hit NPE.
The solution for such requirement for such a right initialization cycle is
abstract public class Session {
final public SessionInfo sessInf;
final public Connection connection;
public Session(SessionInfo sessInf) {
this.sessInf = sessInf;
}
abstract void connect(String uri) throws NullPointerException;
// This block runs after all the constuctors and static members have completed
{
// instance init blocks can initialize final instance objects.
this.connection = connect(sessInf.uri);
}
}
In this way, you will be able to enforce getting connection onto all extension classes and have it done after all constructors have completed.
Describe a task, either with a comment or inherently due to the structure of your code and the identifiers chosen, and then use code blocks to create a hierarchical relationship there where the language itself doesn't enforce one. For example:
public void sendAdminMessage(String msg) throws IOException {
MessageService service; {
String senderKey = properties.get("admin-message-server");
service = MessageService.of(senderKey);
if (!ms.available()) {
throw new MessageServiceException("Not available: " + senderKey);
}
}
/* workaround for issue 1298: Stop sending passwords. */ {
final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
Matcher m = p.matcher(msg);
if (m.matches()) msg = m.group(1) + m.group(2);
}
...
}
The above is just some sample code to explain the concept. The first block is 'documented' by what is immediately preceding it: That block serves to initialize the service variable. The second block is documented by a comment. In both cases, the block provide 'scope' for the comment/variable declaration: They explain where that particular process ends. It's an alternative to this much more common style:
public void sendAdminMessage(String msg) throws IOException {
// START: initialize service
String senderKey = properties.get("admin-message-server");
MessageService service = MessageService.of(senderKey);
if (!ms.available()) {
throw new MessageServiceException("Not available: " + senderKey);
}
// END: initialize service
// START: workaround for issue 1298: Stop sending passwords.
final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
Matcher m = p.matcher(msg);
if (m.matches()) msg = m.group(1) + m.group(2);
// END: workaround for issue 1298: Stop sending passwords.
...
}
The blocks are better, though: They let you use your editor tooling to navigate more efficiently ('go to end of block'), they scope the local variables used within the block so that they cannot escape, and most of all, they align the concept of containment: You are already familiar, as java programmer, with the concept of containment: for blocks, if blocks, method blocks: They are all expressions of hierarchy in code flow. Containment for code for documentary reasons instead of technical is still containment. Why use a different mechanism? Consistency is useful. Less mental load.
NB: Most likely the best design is to isolate the initialisation of the MessageService object to a separate method. However, this does lead to spaghettification: At some point isolating a simple and easily understood task to a method makes it harder to reason about method structure: By isolating it, you've turned the job of initializing the messageservice into a black box (at least, until you look at the helper method), and to fully read the code in order of how it flows, you need to hop around all over your source files. That's usually the better choice (the alternative is very long methods that are hard to test, or reuse parts of), but there are times when it's not. For example, if your block contains references to a significant number of local variables: If you make a helper method you'd have to pass all those variables. A method is also not control flow and local variable transparent (a helper method cannot break out of the loop from the main method, and a helper method cannot see or modify the local variables from the main method). Sometimes that's an impediment.
Team,
Is there possible in java, to know how many active/strong references for a object currently available ?
For example in the below code; Object of class A can be hold by many classes in the project. But i want to print that in the monitor thread.
public class A {
public static A a = new A();
public static A getInstance() {
return a;
}
private A() {
new Monitor(this).start();
}
class Monitor extends Thread {
A refA;
public Monitor(A ref) {
this.refA = ref;
}
public void run () {
//TODO Print how many references currently available for Object A referenced by refA;
//Sure It will be minimum one. (which is "a" in this class A)
}
}
}
Please don't give much importance to this example program. My question is how to find how many strong references available to an object in the heap/stack? Only good thing is we have one strong reference in hand for that object.
If it is not possible in java; can i pass this strong reference to C language; and from C language can i able to do that?
I just wonder how the Profilers/tools are able to do this?
Please help.
No you can't get the exact count without changing the class or branch tools on the VM (which can hardly be made in production due to the impact on performances).
Using the ref package, you can be notified if an object is about to be garbaged (and act at this time) but there is no count available (and not always one handled by the VM).
You can perform a heap dump and analyse it to find the number of references to any object.
What is your requirement for doing this and what will you do with the information as I suspect there is an easier/better way to achieve what you want.
Based on WeakHashMap
/**
* Reference queue for cleared WeakEntries
*/
private final ReferenceQueue<Connection> queue = new ReferenceQueue<>();
List<WeakReference<Connection>> usedConnections = ....
// when you have a new connection
Connection connection = ....
usedConnections.add(new WeakReference(connection, queue));
// checking the queue for discarded objects.
// remove null references from usedConnections
for (Connection x; (x = queue.poll()) != null; ) {
synchronized (queue) {
x.close();
}
}
You may try out somthing like this
Class A
{
static int instanceCount = 0;
public A()
{
instanceCount++;
}
protected finalize()
{
instanceCount--;
}
public static int getInstanceCount()
{
return instanceCount;
}
}
I believe this is the closest you can get to conting references of a class using code. Hope it helps ...
Are there any practical uses of anonymous code blocks in Java?
public static void main(String[] args) {
// in
{
// out
}
}
Please note that this is not about named blocks, i.e.
name: {
if ( /* something */ )
break name;
}
.
They restrict variable scope.
public void foo()
{
{
int i = 10;
}
System.out.println(i); // Won't compile.
}
In practice, though, if you find yourself using such a code block that's probably a sign that you want to refactor that block out to a method.
#David Seiler's answer is right, but I would contend that code blocks are very useful and should be used frequently and don't necessarily indicate the need to factor out into a method. I find they are particularly useful for constructing Swing Component trees, e.g:
JPanel mainPanel = new JPanel(new BorderLayout());
{
JLabel centerLabel = new JLabel();
centerLabel.setText("Hello World");
mainPanel.add(centerLabel, BorderLayout.CENTER);
}
{
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0,0));
{
JLabel label1 = new JLabel();
label1.setText("Hello");
southPanel.add(label1);
}
{
JLabel label2 = new JLabel();
label2.setText("World");
southPanel.add(label2);
}
mainPanel.add(southPanel, BorderLayout.SOUTH);
}
Not only do the code blocks limit the scope of variables as tightly as possible (which is always good, especially when dealing with mutable state and non-final variables), but they also illustrate the component hierarchy much in the way as XML / HTML making the code easier to read, write and maintain.
My issue with factoring out each component instantiation into a method is that
The method will only be used once yet exposed to a wider audience, even if it is a private instance method.
It's harder to read, imagining a deeper more complex component tree, you'd have to drill down to find the code you're interested, and then loose visual context.
In this Swing example, I find that when complexity really does grow beyond manageability it indicates that it's time to factor out a branch of the tree into a new class rather than a bunch of small methods.
It's usually best to make the scope of local variables as small as possible. Anonymous code blocks can help with this.
I find this especially useful with switch statements. Consider the following example, without anonymous code blocks:
public String manipulate(Mode mode) {
switch(mode) {
case FOO:
String result = foo();
tweak(result);
return result;
case BAR:
String result = bar(); // Compiler error
twiddle(result);
return result;
case BAZ:
String rsult = bar(); // Whoops, typo!
twang(result); // No compiler error
return result;
}
}
And with anonymous code blocks:
public String manipulate(Mode mode) {
switch(mode) {
case FOO: {
String result = foo();
tweak(result);
return result;
}
case BAR: {
String result = bar(); // No compiler error
twiddle(result);
return result;
}
case BAZ: {
String rsult = bar(); // Whoops, typo!
twang(result); // Compiler error
return result;
}
}
}
I consider the second version to be cleaner and easier to read. And, it reduces the scope of variables declared within the switch to the case to which they were declared, which in my experience is what you want 99% of the time anyways.
Be warned however, it does not change the behavior for case fall-through - you'll still need to remember to include a break or return to prevent it!
I think you and/or the other answers are confusing two distinct syntactic constructs; namely Instance Initializers and Blocks. (And by the way, a "named block" is really a Labeled Statement, where the Statement happens to be a Block.)
An Instance Initializer is used at the syntactic level of a class member; e.g.
public class Test {
final int foo;
{
// Some complicated initialization sequence; e.g.
int tmp;
if (...) {
...
tmp = ...
} else {
...
tmp = ...
}
foo = tmp;
}
}
The Initializer construct is most commonly used with anonymous classes as per #dfa's example. Another use-case is for doing complicated initialization of 'final' attributes; e.g. see the example above. (However, it is more common to do this using a regular constructor. The pattern above is more commonly used with Static Initializers.)
The other construct is an ordinary block and appears within a code block such as method; e.g.
public void test() {
int i = 1;
{
int j = 2;
...
}
{
int j = 3;
...
}
}
Blocks are most commonly used as part of control statements to group a sequence of statements. But when you use them above, they (just) allow you to restrict the visibility of declarations; e.g. j in the above.
This usually indicates that you need to refactor your code, but it is not always clear cut. For example, you sometimes see this sort of thing in interpreters coded in Java. The statements in the switch arms could be factored into separate methods, but this may result in a significant performance hit for the "inner loop" of an interpreter; e.g.
switch (op) {
case OP1: {
int tmp = ...;
// do something
break;
}
case OP2: {
int tmp = ...;
// do something else
break;
}
...
};
You may use it as constructor for anonymous inner classes.
Like this:
This way you can initialize your object, since the free block is executed during the object construction.
It is not restricted to anonymous inner classes, it applies to regular classes too.
public class SomeClass {
public List data;{
data = new ArrayList();
data.add(1);
data.add(1);
data.add(1);
}
}
Anonymous blocks are useful for limiting the scope of a variable as well as for double brace initialization.
Compare
Set<String> validCodes = new HashSet<String>();
validCodes.add("XZ13s");
validCodes.add("AB21/X");
validCodes.add("YYLEX");
validCodes.add("AR2D");
with
Set<String> validCodes = new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR5E");
}};
Instance initializer block:
class Test {
// this line of code is executed whenever a new instance of Test is created
{ System.out.println("Instance created!"); }
public static void main() {
new Test(); // prints "Instance created!"
new Test(); // prints "Instance created!"
}
}
Anonymous initializer block:
class Test {
class Main {
public void method() {
System.out.println("Test method");
}
}
public static void main(String[] args) {
new Test().new Main() {
{
method(); // prints "Test method"
}
};
{
//=========================================================================
// which means you can even create a List using double brace
List<String> list = new ArrayList<>() {
{
add("el1");
add("el2");
}
};
System.out.println(list); // prints [el1, el2]
}
{
//==========================================================================
// you can even create your own methods for your anonymous class and use them
List<String> list = new ArrayList<String>() {
private void myCustomMethod(String s1, String s2) {
add(s1);
add(s2);
}
{
myCustomMethod("el3", "el4");
}
};
System.out.println(list); // prints [el3, el4]
}
}
}
Variable scope restrict:
class Test {
public static void main() {
{ int i = 20; }
System.out.println(i); // error
}
}
You can use a block to initialize a final variable from the parent scope. This a nice way to limit the scope of some variables only used to initialize the single variable.
public void test(final int x) {
final ClassA a;
final ClassB b;
{
final ClassC parmC = getC(x);
a = parmC.getA();
b = parmC.getB();
}
//... a and b are initialized
}
In general it's preferable to move the block into a method, but this syntax can be nice for one-off cases when multiple variables need to be returned and you don't want to create a wrapper class.
I use the anonymous blocks for all the reasons explained in other answers, which boils down to limiting the scope of variables. I also use them to have proper delimitation of pairs of method belonging together.
Consider the following excerpt:
jg.writeStartObject();
{
jg.writeStringField("fieldName", ((JsonFormFieldDependencyData.FieldLocator) valueOrLocator).getFieldName());
jg.writeStringField("kind", "field");
}
jg.writeEndObject();
Not only you can see at a glance that the methods are properly paired, but doesn't also kind of look like the output too ?
Just be careful to not abuse it and end up in-lining methods ^^
Refer to
Are fields initialized before constructor code is run in Java?
for the order or execution used in this discussion.
Instance init blocks in Java solve initialization problems other languages have been grappling with - what if we need to enforce of perform an instance initialization that must be run but only after all the static intializers and constructors have completed.
Consider this issue is more prevalent in C# with WPF components where sequence of component initialization is tighter. In Java backend such issues are probably resolved by some redesign. So this remains an overly simplistic illustration of the issue.
public class SessionInfo {
public String uri;
..blah, blah ..
}
abstract public class Session {
final public SessionInfo sessInf;
final public Connection connection;
public Session(SessionInfo sessInf) {
this.sessInf = sessInf;
this.connection = connect(sessInf.uri);
}
abstract void connect(String uri) throws NullPointerException;
}
sessInf.uri is looked up by each impl by the impl constructor.
abstract public class SessionImpl extends Session {
public SessionImpl (SessionInfo sessInf) {
super(sessInf);
sessInf.uri = lookUpUri();
}
..blah, blah ..
}
If you trace the flow, you will find that SessionImpl connect would throw NPE, simply because
SessionImpl constructor is run after constructor of parent Session.
therefore sessInf.uri will be null
and connect(sessInf.uri) at parent constructor would hit NPE.
The solution for such requirement for such a right initialization cycle is
abstract public class Session {
final public SessionInfo sessInf;
final public Connection connection;
public Session(SessionInfo sessInf) {
this.sessInf = sessInf;
}
abstract void connect(String uri) throws NullPointerException;
// This block runs after all the constuctors and static members have completed
{
// instance init blocks can initialize final instance objects.
this.connection = connect(sessInf.uri);
}
}
In this way, you will be able to enforce getting connection onto all extension classes and have it done after all constructors have completed.
Describe a task, either with a comment or inherently due to the structure of your code and the identifiers chosen, and then use code blocks to create a hierarchical relationship there where the language itself doesn't enforce one. For example:
public void sendAdminMessage(String msg) throws IOException {
MessageService service; {
String senderKey = properties.get("admin-message-server");
service = MessageService.of(senderKey);
if (!ms.available()) {
throw new MessageServiceException("Not available: " + senderKey);
}
}
/* workaround for issue 1298: Stop sending passwords. */ {
final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
Matcher m = p.matcher(msg);
if (m.matches()) msg = m.group(1) + m.group(2);
}
...
}
The above is just some sample code to explain the concept. The first block is 'documented' by what is immediately preceding it: That block serves to initialize the service variable. The second block is documented by a comment. In both cases, the block provide 'scope' for the comment/variable declaration: They explain where that particular process ends. It's an alternative to this much more common style:
public void sendAdminMessage(String msg) throws IOException {
// START: initialize service
String senderKey = properties.get("admin-message-server");
MessageService service = MessageService.of(senderKey);
if (!ms.available()) {
throw new MessageServiceException("Not available: " + senderKey);
}
// END: initialize service
// START: workaround for issue 1298: Stop sending passwords.
final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
Matcher m = p.matcher(msg);
if (m.matches()) msg = m.group(1) + m.group(2);
// END: workaround for issue 1298: Stop sending passwords.
...
}
The blocks are better, though: They let you use your editor tooling to navigate more efficiently ('go to end of block'), they scope the local variables used within the block so that they cannot escape, and most of all, they align the concept of containment: You are already familiar, as java programmer, with the concept of containment: for blocks, if blocks, method blocks: They are all expressions of hierarchy in code flow. Containment for code for documentary reasons instead of technical is still containment. Why use a different mechanism? Consistency is useful. Less mental load.
NB: Most likely the best design is to isolate the initialisation of the MessageService object to a separate method. However, this does lead to spaghettification: At some point isolating a simple and easily understood task to a method makes it harder to reason about method structure: By isolating it, you've turned the job of initializing the messageservice into a black box (at least, until you look at the helper method), and to fully read the code in order of how it flows, you need to hop around all over your source files. That's usually the better choice (the alternative is very long methods that are hard to test, or reuse parts of), but there are times when it's not. For example, if your block contains references to a significant number of local variables: If you make a helper method you'd have to pass all those variables. A method is also not control flow and local variable transparent (a helper method cannot break out of the loop from the main method, and a helper method cannot see or modify the local variables from the main method). Sometimes that's an impediment.