samples/instanceofclass/src-api2.0/api/InstanceProvider.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 10:04:53 +0200
changeset 210 acf2c31e22d4
parent 209 1c999569643b
permissions -rw-r--r--
Merge: Geertjan's changes to the end of the chapter
     1 
     2 package api;
     3 
     4 // BEGIN: instanceof.class.InstanceProvider2
     5 
     6 import java.util.Arrays;
     7 import java.util.HashSet;
     8 import java.util.Set;
     9 import java.util.concurrent.Callable;
    10 
    11 public final class InstanceProvider {
    12     private final Callable<Object> instance;
    13     private final Set<String> types;
    14 
    15     public InstanceProvider(Callable<Object> instance) {
    16         this.instance = instance;
    17         this.types = null;
    18     }
    19     /** Specifies not only a factory for creating objects, but
    20      * also additional information about them.
    21      * @param instance the factory to create the object
    22      * @param type the class that the create object will be instance of
    23      * @since 2.0 
    24      */
    25     public InstanceProvider(Callable<Object> instance, String... types) {
    26         this.instance = instance;
    27         this.types = new HashSet<String>();
    28         this.types.addAll(Arrays.asList(types));
    29     }
    30     
    31     public Class<?> instanceClass() throws Exception {
    32         return instance.call().getClass();
    33     }
    34     public Object instanceCreate() throws Exception {
    35         return instance.call();
    36     }
    37     
    38     /** Allows to find out if the InstanceProvider creates object of given
    39      * type. This check can be done without loading the actual object or
    40      * its implementation class into memory.
    41      * 
    42      * @param c class to test 
    43      * @return if the instances produced by this provider is instance of c
    44      * @since 2.0 
    45      */
    46     public boolean isInstanceOf(Class<?> c) throws Exception {
    47         if (types != null) {
    48             return types.contains(c.getName());
    49         } else {
    50             // fallback
    51             return c.isAssignableFrom(instanceClass());
    52         }
    53     }
    54 
    55     
    56 }
    57 // END: instanceof.class.InstanceProvider2