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.attributes;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. /**
  20. * Thrown when an attribute has a {@link Target} declaration that forbids
  21. * it being applied to the program element it has been applied to.
  22. *
  23. * <p>For example:
  24. *
  25. * <pre><code>
  26. * / **
  27. * * This attribute can only be applied to Classes.
  28. * * Target(Target.CLASS)
  29. * * /
  30. * public class MyAttribute {}
  31. *
  32. * public class MyClass {
  33. * / **
  34. * * Error: Can't apply MyAttribute to a field!
  35. * * MyAttribute()
  36. * * /
  37. * private String myField;
  38. * }
  39. * </code></pre>
  40. */
  41. public class InvalidAttributeTargetError extends Error {
  42. public InvalidAttributeTargetError (String attributeClass, String element, int targetFlags) {
  43. super ("Attributes of type " + attributeClass + " can't be applied to " + element + ". " +
  44. "They can only be applied to: " + flagsToString (targetFlags));
  45. }
  46. private final static String flagsToString (int flags) {
  47. List targetNames = new ArrayList ();
  48. if ((flags & Target.CLASS) > 0) {
  49. targetNames.add ("CLASS");
  50. }
  51. if ((flags & Target.FIELD) > 0) {
  52. targetNames.add ("FIELD");
  53. }
  54. if ((flags & Target.METHOD) > 0) {
  55. targetNames.add ("METHOD");
  56. }
  57. if ((flags & Target.CONSTRUCTOR) > 0) {
  58. targetNames.add ("CONSTRUCTOR");
  59. }
  60. if ((flags & Target.METHOD_PARAMETER) > 0) {
  61. targetNames.add ("METHOD_PARAMETER");
  62. }
  63. if ((flags & Target.CONSTRUCTOR_PARAMETER) > 0) {
  64. targetNames.add ("CONSTRUCTOR_PARAMETER");
  65. }
  66. if ((flags & Target.RETURN) > 0) {
  67. targetNames.add ("RETURN");
  68. }
  69. StringBuffer sb = new StringBuffer ();
  70. for (int i = 0; i < targetNames.size (); i++) {
  71. sb.append (targetNames.get (i));
  72. if (i < targetNames.size () - 1) {
  73. sb.append (" | ");
  74. }
  75. }
  76. return sb.toString ();
  77. }
  78. }