KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > hivemind > util > Defense


1 // Copyright 2004, 2005 The Apache Software Foundation
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
// http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15 package org.apache.hivemind.util;
16
17 import org.apache.hivemind.HiveMindMessages;
18
19 /**
20  * Simple utilities for defensive programming.
21  *
22  * @author Howard M. Lewis Ship
23  * @since 1.1
24  */

25 public final class Defense
26 {
27     private Defense()
28     {
29         // Prevent instantiation
30
}
31
32     /**
33      * Check for null parameter when not allowed.
34      *
35      * @throws NullPointerException
36      * if parameter is null (the message indicates the name of the parameter).
37      */

38     public static void notNull(Object JavaDoc parameter, String JavaDoc parameterName)
39     {
40         if (parameter == null)
41             throw new NullPointerException JavaDoc(HiveMindMessages.paramNotNull(parameterName));
42     }
43     
44     /**
45      * Check for null field value when not allowed.
46      *
47      * @throws NullPointerException
48      * if field is null (the message indicates the name of the field).
49      */

50    public static void fieldNotNull(Object JavaDoc value, String JavaDoc fieldName)
51     {
52         if (value == null)
53             throw new NullPointerException JavaDoc(HiveMindMessages.fieldNotNull(fieldName));
54     }
55
56     /**
57      * Check that a parameter is not null, and assignable to a particular type.
58      *
59      * @throws ClassCastException
60      * if not assignable (with a useable message)
61      */

62
63     public static void isAssignable(Object JavaDoc parameter, Class JavaDoc expectedType, String JavaDoc parameterName)
64     {
65         Defense.notNull(parameter, parameterName);
66
67         if (!expectedType.isAssignableFrom(parameter.getClass()))
68             throw new ClassCastException JavaDoc(HiveMindMessages.paramWrongType(
69                     parameterName,
70                     parameter,
71                     expectedType));
72     }
73 }
Popular Tags