src/share/classes/com/sun/codemodel/internal/JDefinedClass.java

changeset 1
0961a4a21176
child 45
31822b475baa
equal deleted inserted replaced
-1:000000000000 1:0961a4a21176
1 /*
2 * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Sun designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Sun in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 * CA 95054 USA or visit www.sun.com if you need additional information or
23 * have any questions.
24 */
25
26 package com.sun.codemodel.internal;
27
28 import java.lang.annotation.Annotation;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.Iterator;
33 import java.util.LinkedHashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.TreeMap;
38 import java.util.TreeSet;
39
40 /**
41 * A generated Java class/interface/enum/....
42 *
43 * <p>
44 * This class models a declaration, and since a declaration can be always
45 * used as a reference, it inherits {@link JClass}.
46 *
47 * <h2>Where to go from here?</h2>
48 * <p>
49 * You'd want to generate fields and methods on a class.
50 * See {@link #method(int, JType, String)} and {@link #field(int, JType, String)}.
51 */
52 public class JDefinedClass
53 extends JClass
54 implements JDeclaration, JClassContainer, JGenerifiable, JAnnotatable {
55
56 /** Name of this class. Null if anonymous. */
57 private String name = null;
58
59
60 /** Modifiers for the class declaration */
61 private JMods mods;
62
63 /** Name of the super class of this class. */
64 private JClass superClass;
65
66 /** List of interfaces that this class implements */
67 private final Set<JClass> interfaces = new TreeSet<JClass>();
68
69 /** Fields keyed by their names. */
70 /*package*/ final Map<String,JFieldVar> fields = new LinkedHashMap<String,JFieldVar>();
71
72 /** Static initializer, if this class has one */
73 private JBlock init = null;
74
75 /** class javadoc */
76 private JDocComment jdoc = null;
77
78 /** Set of constructors for this class, if any */
79 private final List<JMethod> constructors = new ArrayList<JMethod>();
80
81 /** Set of methods that are members of this class */
82 private final List<JMethod> methods = new ArrayList<JMethod>();
83
84 /**
85 * Nested classes as a map from name to JDefinedClass.
86 * The name is all capitalized in a case sensitive file system
87 * ({@link JCodeModel#isCaseSensitiveFileSystem}) to avoid conflicts.
88 *
89 * Lazily created to save footprint.
90 *
91 * @see #getClasses()
92 */
93 private Map<String,JDefinedClass> classes;
94
95
96 /**
97 * Flag that controls whether this class should be really generated or not.
98 *
99 * Sometimes it is useful to generate code that refers to class X,
100 * without actually generating the code of X.
101 * This flag is used to surpress X.java file in the output.
102 */
103 private boolean hideFile = false;
104
105 /**
106 * Client-app spcific metadata associated with this user-created class.
107 */
108 public Object metadata;
109
110 /**
111 * String that will be put directly inside the generated code.
112 * Can be null.
113 */
114 private String directBlock;
115
116 /**
117 * If this is a package-member class, this is {@link JPackage}.
118 * If this is a nested class, this is {@link JDefinedClass}.
119 * If this is an anonymous class, this constructor shouldn't be used.
120 */
121 private JClassContainer outer = null;
122
123
124 /** Default value is class or interface
125 * or annotationTypeDeclaration
126 * or enum
127 *
128 */
129 private final ClassType classType;
130
131 /** List containing the enum value declarations
132 *
133 */
134 // private List enumValues = new ArrayList();
135
136 /**
137 * Set of enum constants that are keyed by names.
138 * In Java, enum constant order is actually significant,
139 * because of order ID they get. So let's preserve the order.
140 */
141 private final Map<String,JEnumConstant> enumConstantsByName = new LinkedHashMap<String,JEnumConstant>();
142
143 /**
144 * Annotations on this variable. Lazily created.
145 */
146 private List<JAnnotationUse> annotations = null;
147
148
149 /**
150 * Helper class to implement {@link JGenerifiable}.
151 */
152 private final JGenerifiableImpl generifiable = new JGenerifiableImpl() {
153 protected JCodeModel owner() {
154 return JDefinedClass.this.owner();
155 }
156 };
157
158 JDefinedClass(JClassContainer parent, int mods, String name, ClassType classTypeval) {
159 this(mods, name, parent, parent.owner(), classTypeval);
160 }
161
162 /**
163 * Constructor for creating anonymous inner class.
164 */
165 JDefinedClass(
166 JCodeModel owner,
167 int mods,
168 String name) {
169 this(mods, name, null, owner);
170 }
171
172 private JDefinedClass(
173 int mods,
174 String name,
175 JClassContainer parent,
176 JCodeModel owner) {
177 this (mods,name,parent,owner,ClassType.CLASS);
178 }
179
180 /**
181 * JClass constructor
182 *
183 * @param mods
184 * Modifiers for this class declaration
185 *
186 * @param name
187 * Name of this class
188 */
189 private JDefinedClass(
190 int mods,
191 String name,
192 JClassContainer parent,
193 JCodeModel owner,
194 ClassType classTypeVal) {
195 super(owner);
196
197 if(name!=null) {
198 if (name.trim().length() == 0)
199 throw new IllegalArgumentException("JClass name empty");
200
201 if (!Character.isJavaIdentifierStart(name.charAt(0))) {
202 String msg =
203 "JClass name "
204 + name
205 + " contains illegal character"
206 + " for beginning of identifier: "
207 + name.charAt(0);
208 throw new IllegalArgumentException(msg);
209 }
210 for (int i = 1; i < name.length(); i++) {
211 if (!Character.isJavaIdentifierPart(name.charAt(i))) {
212 String msg =
213 "JClass name "
214 + name
215 + " contains illegal character "
216 + name.charAt(i);
217 throw new IllegalArgumentException(msg);
218 }
219 }
220 }
221
222 this.classType = classTypeVal;
223 if (isInterface())
224 this.mods = JMods.forInterface(mods);
225 else
226 this.mods = JMods.forClass(mods);
227
228 this.name = name;
229
230 this.outer = parent;
231 }
232
233 /**
234 * Returns true if this is an anonymous class.
235 */
236 public final boolean isAnonymous() {
237 return name == null;
238 }
239
240 /**
241 * This class extends the specifed class.
242 *
243 * @param superClass
244 * Superclass for this class
245 *
246 * @return This class
247 */
248 public JDefinedClass _extends(JClass superClass) {
249 if (this.classType==ClassType.INTERFACE)
250 throw new IllegalArgumentException("unable to set the super class for an interface");
251 if (superClass == null)
252 throw new NullPointerException();
253
254 this.superClass = superClass;
255 return this;
256 }
257
258 public JDefinedClass _extends(Class superClass) {
259 return _extends(owner().ref(superClass));
260 }
261
262 /**
263 * Returns the class extended by this class.
264 */
265 public JClass _extends() {
266 if(superClass==null)
267 superClass = owner().ref(Object.class);
268 return superClass;
269 }
270
271 /**
272 * This class implements the specifed interface.
273 *
274 * @param iface
275 * Interface that this class implements
276 *
277 * @return This class
278 */
279 public JDefinedClass _implements(JClass iface) {
280 interfaces.add(iface);
281 return this;
282 }
283
284 public JDefinedClass _implements(Class iface) {
285 return _implements(owner().ref(iface));
286 }
287
288 /**
289 * Returns an iterator that walks the nested classes defined in this
290 * class.
291 */
292 public Iterator<JClass> _implements() {
293 return interfaces.iterator();
294 }
295
296 /**
297 * JClass name accessor.
298 *
299 * <p>
300 * For example, for <code>java.util.List</code>, this method
301 * returns <code>"List"</code>"
302 *
303 * @return Name of this class
304 */
305 public String name() {
306 return name;
307 }
308
309 /**
310 * This method generates reference to the JEnumConstant in
311 * the class
312 *
313 * @param name
314 * The name of the constant.
315 * @return
316 * The generated type-safe enum constant.
317 */
318 public JEnumConstant enumConstant(String name){
319 JEnumConstant ec = new JEnumConstant(this, name);
320 enumConstantsByName.put(name, ec);
321 return ec;
322 }
323
324 /**
325 * Gets the fully qualified name of this class.
326 */
327 public String fullName() {
328 if (outer instanceof JDefinedClass)
329 return ((JDefinedClass) outer).fullName() + '.' + name();
330
331 JPackage p = _package();
332 if (p.isUnnamed())
333 return name();
334 else
335 return p.name() + '.' + name();
336 }
337
338 public String binaryName() {
339 if (outer instanceof JDefinedClass)
340 return ((JDefinedClass) outer).binaryName() + '$' + name();
341 else
342 return fullName();
343 }
344
345 public boolean isInterface() {
346 return this.classType==ClassType.INTERFACE;
347 }
348
349 public boolean isAbstract() {
350 return mods.isAbstract();
351 }
352
353 /**
354 * Adds a field to the list of field members of this JDefinedClass.
355 *
356 * @param mods
357 * Modifiers for this field
358 *
359 * @param type
360 * JType of this field
361 *
362 * @param name
363 * Name of this field
364 *
365 * @return Newly generated field
366 */
367 public JFieldVar field(int mods, JType type, String name) {
368 return field(mods, type, name, null);
369 }
370
371 public JFieldVar field(int mods, Class type, String name) {
372 return field(mods, owner()._ref(type), name);
373 }
374
375 /**
376 * Adds a field to the list of field members of this JDefinedClass.
377 *
378 * @param mods
379 * Modifiers for this field.
380 * @param type
381 * JType of this field.
382 * @param name
383 * Name of this field.
384 * @param init
385 * Initial value of this field.
386 *
387 * @return Newly generated field
388 */
389 public JFieldVar field(
390 int mods,
391 JType type,
392 String name,
393 JExpression init) {
394 JFieldVar f = new JFieldVar(this,JMods.forField(mods), type, name, init);
395
396 if(fields.put(name, f)!=null)
397 throw new IllegalArgumentException("trying to create the same field twice: "+name);
398
399 return f;
400 }
401
402 /** This method indicates if the interface
403 * is an annotationTypeDeclaration
404 *
405 */
406 public boolean isAnnotationTypeDeclaration() {
407 return this.classType==ClassType.ANNOTATION_TYPE_DECL;
408
409
410 }
411
412 /**
413 * Add an annotationType Declaration to this package
414 * @param name
415 * Name of the annotation Type declaration to be added to this package
416 * @return
417 * newly created Annotation Type Declaration
418 * @exception JClassAlreadyExistsException
419 * When the specified class/interface was already created.
420
421 */
422 public JDefinedClass _annotationTypeDeclaration(String name) throws JClassAlreadyExistsException {
423 return _class (JMod.PUBLIC,name,ClassType.ANNOTATION_TYPE_DECL);
424 }
425
426 /**
427 * Add a public enum to this package
428 * @param name
429 * Name of the enum to be added to this package
430 * @return
431 * newly created Enum
432 * @exception JClassAlreadyExistsException
433 * When the specified class/interface was already created.
434
435 */
436 public JDefinedClass _enum (String name) throws JClassAlreadyExistsException {
437 return _class (JMod.PUBLIC,name,ClassType.ENUM);
438 }
439
440 /**
441 * Add a public enum to this package
442 * @param name
443 * Name of the enum to be added to this package
444 * @param mods
445 * Modifiers for this enum declaration
446 * @return
447 * newly created Enum
448 * @exception JClassAlreadyExistsException
449 * When the specified class/interface was already created.
450
451 */
452 public JDefinedClass _enum (int mods,String name) throws JClassAlreadyExistsException {
453 return _class (mods,name,ClassType.ENUM);
454 }
455
456
457
458
459
460 public ClassType getClassType(){
461 return this.classType;
462 }
463
464 public JFieldVar field(
465 int mods,
466 Class type,
467 String name,
468 JExpression init) {
469 return field(mods, owner()._ref(type), name, init);
470 }
471
472 /**
473 * Returns all the fields declred in this class.
474 * The returned {@link Map} is a read-only live view.
475 *
476 * @return always non-null.
477 */
478 public Map<String,JFieldVar> fields() {
479 return Collections.unmodifiableMap(fields);
480 }
481
482 /**
483 * Removes a {@link JFieldVar} from this class.
484 *
485 * @throws IllegalArgumentException
486 * if the given field is not a field on this class.
487 */
488 public void removeField(JFieldVar field) {
489 if(fields.remove(field.name())!=field)
490 throw new IllegalArgumentException();
491 }
492
493 /**
494 * Creates, if necessary, and returns the static initializer
495 * for this class.
496 *
497 * @return JBlock containing initialization statements for this class
498 */
499 public JBlock init() {
500 if (init == null)
501 init = new JBlock();
502 return init;
503 }
504
505 /**
506 * Adds a constructor to this class.
507 *
508 * @param mods
509 * Modifiers for this constructor
510 */
511 public JMethod constructor(int mods) {
512 JMethod c = new JMethod(mods, this);
513 constructors.add(c);
514 return c;
515 }
516
517 /**
518 * Returns an iterator that walks the constructors defined in this class.
519 */
520 public Iterator constructors() {
521 return constructors.iterator();
522 }
523
524 /**
525 * Looks for a method that has the specified method signature
526 * and return it.
527 *
528 * @return
529 * null if not found.
530 */
531 public JMethod getConstructor(JType[] argTypes) {
532 for (JMethod m : constructors) {
533 if (m.hasSignature(argTypes))
534 return m;
535 }
536 return null;
537 }
538
539 /**
540 * Add a method to the list of method members of this JDefinedClass instance.
541 *
542 * @param mods
543 * Modifiers for this method
544 *
545 * @param type
546 * Return type for this method
547 *
548 * @param name
549 * Name of the method
550 *
551 * @return Newly generated JMethod
552 */
553 public JMethod method(int mods, JType type, String name) {
554 // XXX problems caught in M constructor
555 JMethod m = new JMethod(this, mods, type, name);
556 methods.add(m);
557 return m;
558 }
559
560 public JMethod method(int mods, Class type, String name) {
561 return method(mods, owner()._ref(type), name);
562 }
563
564 /**
565 * Returns the set of methods defined in this class.
566 */
567 public Collection<JMethod> methods() {
568 return methods;
569 }
570
571 /**
572 * Looks for a method that has the specified method signature
573 * and return it.
574 *
575 * @return
576 * null if not found.
577 */
578 public JMethod getMethod(String name, JType[] argTypes) {
579 outer :
580 for (JMethod m : methods) {
581 if (!m.name().equals(name))
582 continue;
583
584 if (m.hasSignature(argTypes))
585 return m;
586 }
587 return null;
588 }
589
590 public boolean isClass() {
591 return true;
592 }
593 public boolean isPackage() {
594 return false;
595 }
596 public JPackage getPackage() { return parentContainer().getPackage(); }
597
598 /**
599 * Add a new nested class to this class.
600 *
601 * @param mods
602 * Modifiers for this class declaration
603 *
604 * @param name
605 * Name of class to be added to this package
606 *
607 * @return Newly generated class
608 */
609 public JDefinedClass _class(int mods, String name)
610 throws JClassAlreadyExistsException {
611 return _class(mods, name, ClassType.CLASS);
612 }
613
614 /**
615 * {@inheritDoc}
616 *
617 * @deprecated
618 */
619 public JDefinedClass _class(int mods, String name, boolean isInterface) throws JClassAlreadyExistsException {
620 return _class(mods,name,isInterface?ClassType.INTERFACE:ClassType.CLASS);
621 }
622
623 public JDefinedClass _class(int mods, String name, ClassType classTypeVal)
624 throws JClassAlreadyExistsException {
625
626 String NAME;
627 if (JCodeModel.isCaseSensitiveFileSystem)
628 NAME = name.toUpperCase();
629 else
630 NAME = name;
631
632 if (getClasses().containsKey(NAME))
633 throw new JClassAlreadyExistsException(getClasses().get(NAME));
634 else {
635 // XXX problems caught in the NC constructor
636 JDefinedClass c = new JDefinedClass(this, mods, name, classTypeVal);
637 getClasses().put(NAME,c);
638 return c;
639 }
640 }
641
642 /**
643 * Add a new public nested class to this class.
644 */
645 public JDefinedClass _class(String name)
646 throws JClassAlreadyExistsException {
647 return _class(JMod.PUBLIC, name);
648 }
649
650 /**
651 * Add an interface to this package.
652 *
653 * @param mods
654 * Modifiers for this interface declaration
655 *
656 * @param name
657 * Name of interface to be added to this package
658 *
659 * @return Newly generated interface
660 */
661 public JDefinedClass _interface(int mods, String name)
662 throws JClassAlreadyExistsException {
663 return _class(mods, name, ClassType.INTERFACE);
664 }
665
666 /**
667 * Adds a public interface to this package.
668 */
669 public JDefinedClass _interface(String name)
670 throws JClassAlreadyExistsException {
671 return _interface(JMod.PUBLIC, name);
672 }
673
674 /**
675 * Creates, if necessary, and returns the class javadoc for this
676 * JDefinedClass
677 *
678 * @return JDocComment containing javadocs for this class
679 */
680 public JDocComment javadoc() {
681 if (jdoc == null)
682 jdoc = new JDocComment(owner());
683 return jdoc;
684 }
685
686 /**
687 * Mark this file as hidden, so that this file won't be
688 * generated.
689 *
690 * <p>
691 * This feature could be used to generate code that refers
692 * to class X, without actually generating X.java.
693 */
694 public void hide() {
695 hideFile = true;
696 }
697
698 public boolean isHidden() {
699 return hideFile;
700 }
701
702 /**
703 * Returns an iterator that walks the nested classes defined in this
704 * class.
705 */
706 public final Iterator<JDefinedClass> classes() {
707 if(classes==null)
708 return Collections.<JDefinedClass>emptyList().iterator();
709 else
710 return classes.values().iterator();
711 }
712
713 private Map<String,JDefinedClass> getClasses() {
714 if(classes==null)
715 classes = new TreeMap<String,JDefinedClass>();
716 return classes;
717 }
718
719
720 /**
721 * Returns all the nested classes defined in this class.
722 */
723 public final JClass[] listClasses() {
724 if(classes==null)
725 return new JClass[0];
726 else
727 return classes.values().toArray(new JClass[classes.values().size()]);
728 }
729
730 @Override
731 public JClass outer() {
732 if (outer.isClass())
733 return (JClass) outer;
734 else
735 return null;
736 }
737
738 public void declare(JFormatter f) {
739 if (jdoc != null)
740 f.nl().g(jdoc);
741
742 if (annotations != null){
743 for( int i=0; i<annotations.size(); i++ )
744 f.g(annotations.get(i)).nl();
745 }
746
747 f.g(mods).p(classType.declarationToken).id(name).d(generifiable);
748
749 if (superClass != null && superClass != owner().ref(Object.class))
750 f.nl().i().p("extends").g(superClass).nl().o();
751
752 if (!interfaces.isEmpty()) {
753 if (superClass == null)
754 f.nl();
755 f.i().p(classType==ClassType.INTERFACE ? "extends" : "implements");
756 f.g(interfaces);
757 f.nl().o();
758 }
759 declareBody(f);
760 }
761
762 /**
763 * prints the body of a class.
764 */
765 protected void declareBody(JFormatter f) {
766 f.p('{').nl().nl().i();
767 boolean first = true;
768
769 if (!enumConstantsByName.isEmpty()) {
770 for (JEnumConstant c : enumConstantsByName.values()) {
771 if (!first) f.p(',').nl();
772 f.d(c);
773 first = false;
774 }
775 f.p(';').nl();
776 }
777
778 for( JFieldVar field : fields.values() )
779 f.d(field);
780 if (init != null)
781 f.nl().p("static").s(init);
782 for (JMethod m : constructors) {
783 f.nl().d(m);
784 }
785 for (JMethod m : methods) {
786 f.nl().d(m);
787 }
788 if(classes!=null)
789 for (JDefinedClass dc : classes.values())
790 f.nl().d(dc);
791
792
793 if (directBlock != null)
794 f.p(directBlock);
795 f.nl().o().p('}').nl();
796 }
797
798 /**
799 * Places the given string directly inside the generated class.
800 *
801 * This method can be used to add methods/fields that are not
802 * generated by CodeModel.
803 * This method should be used only as the last resort.
804 */
805 public void direct(String string) {
806 if (directBlock == null)
807 directBlock = string;
808 else
809 directBlock += string;
810 }
811
812 public final JPackage _package() {
813 JClassContainer p = outer;
814 while (!(p instanceof JPackage))
815 p = p.parentContainer();
816 return (JPackage) p;
817 }
818
819 public final JClassContainer parentContainer() {
820 return outer;
821 }
822
823 public JTypeVar generify(String name) {
824 return generifiable.generify(name);
825 }
826 public JTypeVar generify(String name, Class bound) {
827 return generifiable.generify(name, bound);
828 }
829 public JTypeVar generify(String name, JClass bound) {
830 return generifiable.generify(name, bound);
831 }
832 @Override
833 public JTypeVar[] typeParams() {
834 return generifiable.typeParams();
835 }
836
837 protected JClass substituteParams(
838 JTypeVar[] variables,
839 List<JClass> bindings) {
840 return this;
841 }
842
843 /** Adding ability to annotate a class
844 * @param clazz
845 * The annotation class to annotate the class with
846 */
847 public JAnnotationUse annotate(Class <? extends Annotation> clazz){
848 return annotate(owner().ref(clazz));
849 }
850
851 /** Adding ability to annotate a class
852 * @param clazz
853 * The annotation class to annotate the class with
854 */
855 public JAnnotationUse annotate(JClass clazz){
856 if(annotations==null)
857 annotations = new ArrayList<JAnnotationUse>();
858 JAnnotationUse a = new JAnnotationUse(clazz);
859 annotations.add(a);
860 return a;
861 }
862
863 public <W extends JAnnotationWriter> W annotate2(Class<W> clazz) {
864 return TypedAnnotationWriter.create(clazz,this);
865 }
866 }

mercurial