1 package bsh; 2 3 import java.util.Hashtable ; 4 5 9 12 public class Modifiers implements java.io.Serializable 13 { 14 public static final int CLASS=0, METHOD=1, FIELD=2; 15 Hashtable modifiers; 16 17 20 public void addModifier( int context, String name ) 21 { 22 if ( modifiers == null ) 23 modifiers = new Hashtable (); 24 25 Object existing = modifiers.put( name, Void.TYPE ); 26 if ( existing != null ) 27 throw new IllegalStateException ("Duplicate modifier: "+ name ); 28 29 int count = 0; 30 if ( hasModifier("private") ) ++count; 31 if ( hasModifier("protected") ) ++count; 32 if ( hasModifier("public") ) ++count; 33 if ( count > 1 ) 34 throw new IllegalStateException ( 35 "public/private/protected cannot be used in combination." ); 36 37 switch( context ) 38 { 39 case CLASS: 40 validateForClass(); 41 break; 42 case METHOD: 43 validateForMethod(); 44 break; 45 case FIELD: 46 validateForField(); 47 break; 48 } 49 } 50 51 public boolean hasModifier( String name ) 52 { 53 if ( modifiers == null ) 54 modifiers = new Hashtable (); 55 return modifiers.get(name) != null; 56 } 57 58 private void validateForMethod() 60 { 61 insureNo("volatile", "Method"); 62 insureNo("transient", "Method"); 63 } 64 private void validateForField() 65 { 66 insureNo("synchronized", "Variable"); 67 insureNo("native", "Variable"); 68 insureNo("abstract", "Variable"); 69 } 70 private void validateForClass() 71 { 72 validateForMethod(); insureNo("native", "Class"); 74 insureNo("synchronized", "Class"); 75 } 76 77 private void insureNo( String modifier, String context ) 78 { 79 if ( hasModifier( modifier ) ) 80 throw new IllegalStateException ( 81 context + " cannot be declared '"+modifier+"'"); 82 } 83 84 public String toString() 85 { 86 return "Modifiers: "+modifiers; 87 } 88 89 } 90 | Popular Tags |