16.4. Implementing InterfacesA remarkable feature of Java as of version 1.3 is that it is possible for a class to dynamically implement an interface at run time. This feature is relatively unknown. Readers who have not previously encountered it may wish to read more details in Appendix A.This ability ties very nicely into scripting. A special class could intercept any method call into an interface and could pass the arguments to a scripted function. This makes it very easy to change the implementation of an interface; new code can be developed and installed on the fly without needing to recompile or restart anything.Listing 16.3 shows a sample interface that provides methods to deal with prime numbers. There are many many algorithms for computing prime numbers and checking numbers for primality; each has different advantages and disadvantages. It therefore makes sense to declare this as an interface. Listing 16.3. An interface with prime methodsPrime numbers are useful in a wide variety of applications, notably cryptography. Listing 16.4 shows a more artificial example, a class with one method that returns a list of prime numbers and another method that determines whether the current day of the month is a prime. Listing 16.4. A class that uses primesNormally the next step would be to create one or more Java implementations of PrimeInterface with different characteristics and perhaps experiment with their performance. However, it is much easier to write these in BeanShell, where they can be more rapidly tweaked and tested. Implementing an interface in BeanShell looks much like anonymous classes in Java. In this case the code will consist of new PrimeInterface() {...} with the relevant code inside the braces. Here is one such implementation: The implementation of isPrime() simply checks all numbers between 2 and half of the given number to determine if any is a factor.[1] getPrime() obtains the n th prime iteratively by checking to see if any of the previously obtained primes is a factor of the current candidate. [1] Even this is doing too much work. It is only necessary to check up to the square root of the number. This would be an easy optimization to make in BeanShell! It is quite easy to use this implementation in conjunction with a PrimeUser:
|