Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to use anonymous classes in java

 
sony vijay
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just like any class that implements Check, you can simply use a Check reference and call the method(s) from Check:
 
Campbell Ritchie
Sheriff
Posts: 48402
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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
Posts: 48402
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48402
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are bound to be different. Start looking here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic