1. /*
  2. * Copyright 2003-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.collections.bag;
  17. import org.apache.commons.collections.Bag;
  18. import org.apache.commons.collections.functors.InstanceofPredicate;
  19. /**
  20. * Decorates another <code>Bag</code> to validate that elements added
  21. * are of a specific type.
  22. * <p>
  23. * The validation of additions is performed via an instanceof test against
  24. * a specified <code>Class</code>. If an object cannot be added to the
  25. * collection, an IllegalArgumentException is thrown.
  26. *
  27. * @since Commons Collections 3.0
  28. * @version $Revision: 1.6 $ $Date: 2004/05/15 12:27:04 $
  29. *
  30. * @author Stephen Colebourne
  31. * @author Matthew Hawthorne
  32. */
  33. public class TypedBag {
  34. /**
  35. * Factory method to create a typed bag.
  36. * <p>
  37. * If there are any elements already in the bag being decorated, they
  38. * are validated.
  39. *
  40. * @param bag the bag to decorate, must not be null
  41. * @param type the type to allow into the bag, must not be null
  42. * @return a new typed Bag
  43. * @throws IllegalArgumentException if bag or type is null
  44. * @throws IllegalArgumentException if the bag contains invalid elements
  45. */
  46. public static Bag decorate(Bag bag, Class type) {
  47. return new PredicatedBag(bag, InstanceofPredicate.getInstance(type));
  48. }
  49. /**
  50. * Restrictive constructor.
  51. */
  52. protected TypedBag() {
  53. super();
  54. }
  55. }