1 33 package net.sf.jga.fn.property; 34 35 import java.text.MessageFormat ; 36 import net.sf.jga.fn.UnaryFunctor; 37 38 47 48 public class Cast<T,R> extends UnaryFunctor<T,R> { 49 50 static final long serialVersionUID = 2712605844695159349L; 51 52 private Class <R> _class; 53 54 59 public Cast(Class <R> cl) { 60 if (cl == null) 61 throw new IllegalArgumentException ("A class must be given"); 62 63 _class = cl; 64 } 65 66 67 public Class <R> getCastClass() { return _class; } 68 69 71 public R fn(T arg) { 72 79 if (_class.isInstance(arg)) 80 return (R) arg; 81 82 String msg = "Cannot cast [{0}] to class {1}"; 83 Object [] args = new Object []{arg, _class.getName()}; 84 ClassCastException x = new ClassCastException (MessageFormat.format(msg, args)); 85 throw x; 86 } 87 88 92 public void accept(net.sf.jga.fn.Visitor v) { 93 if (v instanceof Cast.Visitor) 94 ((Cast.Visitor)v).visit(this); 95 else 96 v.visit(this); 97 } 98 99 101 public String toString() { 102 return "Cast["+_class.getName()+"]"; 103 } 104 105 107 111 public interface Visitor extends net.sf.jga.fn.Visitor { 112 public void visit(Cast host); 113 } 114 } 115 | Popular Tags |