KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > bsh > Modifiers


1 package bsh;
2
3 import java.util.Hashtable JavaDoc;
4
5 /**
6     
7     @author Pat Niemeyer (pat@pat.net)
8 */

9 /*
10     Note: which of these things should be checked at parse time vs. run time?
11 */

12 public class Modifiers implements java.io.Serializable JavaDoc
13 {
14     public static final int CLASS=0, METHOD=1, FIELD=2;
15     Hashtable JavaDoc modifiers;
16
17     /**
18         @param context is METHOD or FIELD
19     */

20     public void addModifier( int context, String JavaDoc name )
21     {
22         if ( modifiers == null )
23             modifiers = new Hashtable JavaDoc();
24
25         Object JavaDoc existing = modifiers.put( name, Void.TYPE/*arbitrary flag*/ );
26         if ( existing != null )
27             throw new IllegalStateException JavaDoc("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 JavaDoc(
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 JavaDoc name )
52     {
53         if ( modifiers == null )
54             modifiers = new Hashtable JavaDoc();
55         return modifiers.get(name) != null;
56     }
57
58     // could refactor these a bit
59
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(); // volatile, transient
73
insureNo("native", "Class");
74         insureNo("synchronized", "Class");
75     }
76
77     private void insureNo( String JavaDoc modifier, String JavaDoc context )
78     {
79         if ( hasModifier( modifier ) )
80             throw new IllegalStateException JavaDoc(
81                 context + " cannot be declared '"+modifier+"'");
82     }
83
84     public String JavaDoc toString()
85     {
86         return "Modifiers: "+modifiers;
87     }
88
89 }
90
Popular Tags