| Author |
How to use anonymous classes in java
|
sony vijay
Ranch Hand
Joined: Jun 27, 2010
Posts: 32
|
|
Hi,
I am trying to perform some rule checking in my application. I am using an inner interface(Check) within a class and am creating anonymous classes of the type interface(Check). Using this approach, the idea is to create an anonymous class for each rule. Please see code below:
But, I am not sure how to call the methods of anonymous classes from another class? Say, there's another class called TypeCheck. How do I call the IS_NUMBER.check method?
I have never used interfaces with anonymous classes before and I am trying this out. Thank YOU!
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Just like any class that implements Check, you can simply use a Check reference and call the method(s) from Check:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
And the Check instances should probably be marked final.
How are you going to check whether a String is a regular expression? That seems impossible to me.
|
 |
sony vijay
Ranch Hand
Joined: Jun 27, 2010
Posts: 32
|
|
@Campbell Ritchie: I would use the the java regex Patterns to check whether a string is a regular expression:
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
I would do a Patter.compile(input) within a try-catch block. The catch block would throw a PatternSyntaxException. I hope you get the general idea. Please let me know if you need more explanation. But, I am not sure whether the the java Pattern of regular expressions matches the javascript regular expression patterns. I am yet to check on that.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
I see what you mean, but you can only check for syntax errors, not what the regular expression will test for.
|
 |
sony vijay
Ranch Hand
Joined: Jun 27, 2010
Posts: 32
|
|
|
Thanks! That was a useful link. But, I am trying to just check the syntax errors for now. Any idea if there are any differences between Java and Javascript regular expressions?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
|
They are bound to be different. Start looking here.
|
 |
 |
|
|
subject: How to use anonymous classes in java
|
|
|