• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  contributor license agreements.  See the NOTICE file distributed with
3  *  this work for additional information regarding copyright ownership.
4  *  The ASF licenses this file to You under the Apache License, Version 2.0
5  *  (the "License"); you may not use this file except in compliance with
6  *  the License.  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 
17 package libcore.java.lang;
18 
19 import libcore.test.annotation.NonCts;
20 import libcore.test.reasons.NonCtsReasons;
21 
22 import java.io.File;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.Serializable;
26 import java.lang.annotation.Annotation;
27 import java.lang.annotation.Retention;
28 import java.lang.annotation.RetentionPolicy;
29 import java.lang.reflect.Constructor;
30 import java.lang.reflect.Field;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.ParameterizedType;
33 import java.lang.reflect.Type;
34 import java.lang.reflect.TypeVariable;
35 import java.net.URL;
36 import java.net.URLClassLoader;
37 import java.util.AbstractList;
38 import java.util.Collection;
39 import java.util.List;
40 import java.util.Vector;
41 import tests.support.Support_ClassLoader;
42 import tests.support.resource.Support_Resources;
43 
44 @SuppressWarnings("deprecation")
45 public class OldClassTest extends junit.framework.TestCase {
46     final String packageName = getClass().getPackage().getName();
47     final String classNameInitError1 = packageName + ".TestClass1";
48     final String classNameInitError2 = packageName + ".TestClass1B";
49     final String classNameLinkageError = packageName + ".TestClass";
50     final String sourceJARfile = "illegalClasses.jar";
51     final String illegalClassName = "illegalClass";
52 
53     @Retention(RetentionPolicy.RUNTIME)
54     public @interface TestAnnotation {
value()55         String value();
56     }
57 
58     public static class TestClass1C {
59         static TestClass2 tc = new TestClass2(0);
60 
TestClass1C()61         TestClass1C() {
62         }
63 
64     }
65 
66     public static class TestClass2 {
67 
TestClass2(int i)68         public TestClass2(int i) throws IllegalArgumentException {
69             throw new IllegalArgumentException();
70         }
71     }
72 
73     public static class TestClass3 {
TestClass3()74         private TestClass3() {}
75     }
76 
77     interface TestInterface {
78         public static int TEST_INTERFACE_FIELD = 0;
79 
getCount()80         int getCount();
setCount(int value)81         void setCount(int value);
82     }
83 
84     static class StaticMember$Class {
85         class Member2$A {
86         }
87     }
88 
89     class Member$Class {
90         class Member3$B {
91         }
92     }
93 
94     @Deprecated
95     @TestAnnotation("libcore.java.lang.OldClassTest$ExtendTestClass")
96     public static class ExtendTestClass extends PublicTestClass {
97 
98         private static final long serialVersionUID = 1L;
99 
100         public enum enumExm {ONE, TWO, THREE};
101         @Override
setCount(int value)102         public void setCount(int value) {
103 
104         }
105     }
106 
107     public class ExtendTestClass1 extends ExtendTestClass {
108 
109     }
110 
111     @TestAnnotation("libcore.java.lang.OldClassTest$PublicTestClass")
112     public static class PublicTestClass implements TestInterface, Serializable, Cloneable {
113 
114         private static final long serialVersionUID = 1L;
115 
116         public static String TEST_FIELD = "test field";
117 
118         Object clazz;
119 
PublicTestClass()120         public PublicTestClass() {
121             class LocalClass { }
122 
123             clazz = new LocalClass();
124         }
125 
getLocalClass()126         public Object getLocalClass() {
127             class LocalClass {}
128             Object returnedObject = new LocalClass();
129             return returnedObject;
130         }
131 
132         int count = 0;
133 
getCount()134         public int getCount() {
135             return count;
136         }
137 
setCount(int value)138         public void setCount(int value) {
139             count = value;
140         }
141 
142         private class PrivateClass1 {
143 
toString()144             public String toString() {
145                 return "PrivateClass0";
146             }
147         }
148 
149         public class PrivateClass2 {
150 
toString()151             public String toString() {
152                 return "PrivateClass1";
153             }
154         }
155     }
156 
157     public static class TestClass {
158         @SuppressWarnings("unused")
159         private int privField = 1;
160 
161         public int pubField = 2;
162 
163         private Object cValue = null;
164 
165         public Object ack = new Object();
166 
167         @SuppressWarnings("unused")
privMethod()168         private int privMethod() {
169             return 1;
170         }
171 
pubMethod()172         public int pubMethod() {
173             return 2;
174         }
175 
cValue()176         public Object cValue() {
177             return cValue;
178         }
179 
TestClass()180         public TestClass() {
181         }
182 
183         @SuppressWarnings("unused")
TestClass(Object o)184         private TestClass(Object o) {
185         }
186     }
187 
188     public static class SubTestClass extends TestClass {
189     }
190 
191     interface Intf1 {
192         public int field1 = 1;
193         public int field2 = 1;
test()194         void test();
195     }
196 
197     interface Intf2 {
198         public int field1 = 1;
test()199         void test();
200     }
201 
202     interface Intf3 extends Intf1 {
203         public int field1 = 1;
204     }
205 
206     interface Intf4 extends Intf1, Intf2 {
207         public int field1 = 1;
test2(int a, Object b)208         void test2(int a, Object b);
209     }
210 
211     interface Intf5 extends Intf1 {
212     }
213 
214     class Cls1 implements Intf2 {
215         public int field1 = 2;
216         public int field2 = 2;
test()217         public void test() {
218         }
219     }
220 
221     class Cls2 extends Cls1 implements Intf1 {
222         public int field1 = 2;
223         @Override
test()224         public void test() {
225         }
226     }
227 
228     class Cls3 implements Intf3, Intf4 {
test()229         public void test() {
230         }
test2(int a, Object b)231         public void test2(int a, Object b) {
232         }
233     }
234 
235     static class Cls4 {
236 
237     }
238 
test_getAnnotations()239     public void test_getAnnotations() {
240       Annotation [] annotations = PublicTestClass.class.getAnnotations();
241       assertEquals(1, annotations.length);
242       assertEquals(TestAnnotation.class, annotations[0].annotationType());
243 
244       annotations = ExtendTestClass.class.getAnnotations();
245       assertEquals(2, annotations.length);
246 
247       for(int i = 0; i < annotations.length; i++) {
248           Class<? extends Annotation> type = annotations[i].annotationType();
249           assertTrue("Annotation's type " + i + ": " + type,
250               type.equals(Deprecated.class) ||
251               type.equals(TestAnnotation.class));
252       }
253     }
254 
test_forNameLjava_lang_StringLbooleanLClassLoader()255     public void test_forNameLjava_lang_StringLbooleanLClassLoader() throws Exception {
256 
257         ClassLoader pcl = getClass().getClassLoader();
258 
259         Class<?> [] classes = {PublicTestClass.class, ExtendTestClass.class,
260                 ExtendTestClass1.class, TestInterface.class, String.class};
261 
262         for(int i = 0; i < classes.length; i++) {
263             Class<?> clazz = Class.forName(classes[i].getName(), true, pcl);
264             assertEquals(classes[i], clazz);
265 
266             clazz = Class.forName(classes[i].getName(), false, pcl);
267             assertEquals(classes[i], clazz);
268         }
269 
270         Class<?> [] systemClasses = {String.class, Integer.class, Object.class,
271                 Object[].class};
272 
273         for(int i = 0; i < systemClasses.length; i++) {
274             Class<?> clazz = Class.forName(systemClasses[i].getName(), true,
275                                             ClassLoader.getSystemClassLoader());
276             assertEquals(systemClasses[i], clazz);
277 
278             clazz = Class.forName(systemClasses[i].getName(), false,
279                                             ClassLoader.getSystemClassLoader());
280             assertEquals(systemClasses[i], clazz);
281         }
282 
283         try  {
284             Class.forName(null, true, pcl);
285             fail("NullPointerException is not thrown.");
286         } catch(NullPointerException  npe) {
287             //expected
288         }
289 
290         try {
291             Class.forName("NotExistClass", true, pcl);
292             fail("ClassNotFoundException is not thrown for non existent class.");
293         } catch(ClassNotFoundException cnfe) {
294             //expected
295         }
296 
297         try {
298             Class.forName("String", false, pcl);
299             fail("ClassNotFoundException is not thrown for non existent class.");
300         } catch(ClassNotFoundException cnfe) {
301             //expected
302         }
303 
304         try {
305             Class.forName("libcore.java.lang.NonexistentClass", false, pcl);
306             fail("ClassNotFoundException is not thrown for non existent class.");
307         } catch(ClassNotFoundException cnfe) {
308             //expected
309         }
310     }
311 
312     // Android-note: Class.forName method throws ClassNotFoundException on Android.
test_forNameLjava_lang_StringLbooleanLClassLoader_AndroidOnly()313     public void test_forNameLjava_lang_StringLbooleanLClassLoader_AndroidOnly() throws Exception {
314 
315         // Android doesn't support loading class files from a jar.
316         try {
317 
318             URL url = getClass().getClassLoader().getResource(
319                     packageName.replace(".", "/") + "/" + sourceJARfile);
320 
321             ClassLoader loader = new URLClassLoader(new URL[] { url },
322                     getClass().getClassLoader());
323             try {
324                 Class.forName(classNameLinkageError, true, loader);
325                 fail("LinkageError or ClassNotFoundException expected.");
326             } catch (java.lang.LinkageError le) {
327                 // Expected for the RI.
328             } catch (java.lang.ClassNotFoundException ce) {
329                 // Expected for Android.
330             }
331         } catch(Exception e) {
332             fail("Unexpected exception was thrown: " + e.toString());
333         }
334 
335         try {
336             Class.forName(classNameInitError2,
337                     true, getClass().getClassLoader());
338             fail("ExceptionInInitializerError or ClassNotFoundException " +
339             "should be thrown.");
340         } catch (java.lang.ExceptionInInitializerError ie) {
341             // Expected for the RI.
342         // Remove this comment to let the test pass on Android.
343         } catch (java.lang.ClassNotFoundException ce) {
344             // Expected for Android.
345         }
346     }
347 
test_getAnnotation()348     public void test_getAnnotation() {
349       TestAnnotation target = PublicTestClass.class.getAnnotation(TestAnnotation.class);
350       assertEquals(target.value(), PublicTestClass.class.getName());
351 
352       assertNull(PublicTestClass.class.getAnnotation(Deprecated.class));
353 
354       Deprecated target2 = ExtendTestClass.class.getAnnotation(Deprecated.class);
355       assertNotNull(target2);
356     }
357 
test_getDeclaredAnnotations()358     public void test_getDeclaredAnnotations() {
359         Annotation [] annotations = PublicTestClass.class.getDeclaredAnnotations();
360         assertEquals(1, annotations.length);
361 
362         annotations = ExtendTestClass.class.getDeclaredAnnotations();
363         assertEquals(2, annotations.length);
364 
365         annotations = TestInterface.class.getDeclaredAnnotations();
366         assertEquals(0, annotations.length);
367 
368         annotations = String.class.getDeclaredAnnotations();
369         assertEquals(0, annotations.length);
370     }
371 
test_getEnclosingClass()372     public void test_getEnclosingClass() {
373         Class clazz = OldClassTest.class.getEnclosingClass();
374         assertNull(clazz);
375 
376         assertEquals(getClass(), Cls1.class.getEnclosingClass());
377         assertEquals(getClass(), Intf1.class.getEnclosingClass());
378         assertEquals(getClass(), Cls4.class.getEnclosingClass());
379     }
380 
test_getEnclosingMethod()381     public void test_getEnclosingMethod() {
382         Method clazz = ExtendTestClass.class.getEnclosingMethod();
383         assertNull(clazz);
384 
385         PublicTestClass ptc = new PublicTestClass();
386         try {
387             assertEquals("getEnclosingMethod returns incorrect method.",
388                     PublicTestClass.class.getMethod("getLocalClass",
389                             (Class []) null),
390                     ptc.getLocalClass().getClass().getEnclosingMethod());
391         } catch(NoSuchMethodException nsme) {
392             fail("NoSuchMethodException was thrown.");
393         }
394     }
395 
test_getEnclosingConstructor()396     public void test_getEnclosingConstructor() {
397 
398         PublicTestClass ptc = new PublicTestClass();
399 
400         assertEquals("getEnclosingConstructor method returns incorrect class.",
401                 PublicTestClass.class.getConstructors()[0],
402                 ptc.clazz.getClass().getEnclosingConstructor());
403 
404         assertNull("getEnclosingConstructor should return null for local " +
405                 "class declared in method.",
406                 ptc.getLocalClass().getClass().getEnclosingConstructor());
407 
408         assertNull("getEnclosingConstructor should return null for local " +
409                 "class declared in method.",
410                 ExtendTestClass.class.getEnclosingConstructor());
411     }
412 
413 
test_getEnumConstants()414     public void test_getEnumConstants() {
415         Object [] clazz = ExtendTestClass.class.getEnumConstants();
416         assertNull(clazz);
417         Object [] constants = TestEnum.class.getEnumConstants();
418         assertEquals(TestEnum.values().length, constants.length);
419         for(int i = 0; i < constants.length; i++) {
420             assertEquals(TestEnum.values()[i], constants[i]);
421         }
422         assertEquals(0, TestEmptyEnum.class.getEnumConstants().length);
423     }
424     public enum TestEnum {
425         ONE, TWO, THREE
426     }
427     public enum TestEmptyEnum {
428     }
429 
430     @NonCts(bug = 338503591, reason = NonCtsReasons.NON_BREAKING_BEHAVIOR_FIX)
test_getGenericInterfaces()431     public void test_getGenericInterfaces() {
432         Type [] types = ExtendTestClass1.class.getGenericInterfaces();
433         assertEquals(0, types.length);
434 
435         Class [] interfaces = {TestInterface.class, Serializable.class,
436                                Cloneable.class};
437         types = PublicTestClass.class.getGenericInterfaces();
438         assertEquals(interfaces.length, types.length);
439         for(int i = 0; i < types.length; i++) {
440             assertEquals(interfaces[i], types[i]);
441         }
442 
443         types = TestInterface.class.getGenericInterfaces();
444         assertEquals(0, types.length);
445 
446         types = Collection.class.getGenericInterfaces();
447         assertEquals(1, types.length);
448         assertEquals(Iterable.class, ((ParameterizedType)types[0]).getRawType());
449 
450         assertEquals(0, int.class.getGenericInterfaces().length);
451         assertEquals(0, void.class.getGenericInterfaces().length);
452     }
453 
test_getGenericSuperclass()454     public void test_getGenericSuperclass () {
455         assertEquals(PublicTestClass.class,
456                                   ExtendTestClass.class.getGenericSuperclass());
457         assertEquals(ExtendTestClass.class,
458                 ExtendTestClass1.class.getGenericSuperclass());
459         assertEquals(Object.class, PublicTestClass.class.getGenericSuperclass());
460         assertEquals(Object.class, String.class.getGenericSuperclass());
461         assertEquals(null, TestInterface.class.getGenericSuperclass());
462 
463         ParameterizedType type = (ParameterizedType) Vector.class.getGenericSuperclass();
464         assertEquals(AbstractList.class, type.getRawType());
465     }
466 
467     // Android-note: Uses dalvik.system.PathClassLoader.
468     // Different behavior between cts host and run-core-test")
test_getPackage()469     public void test_getPackage() {
470 
471       Package thisPackage = getClass().getPackage();
472       assertEquals("libcore.java.lang",
473                       thisPackage.getName());
474 
475       Package stringPackage = String.class.getPackage();
476       assertEquals("java.lang", stringPackage.getName());
477 
478       String hyts_package_name = "hyts_package_dex.jar";
479       File resources = Support_Resources.createTempFolder();
480       Support_Resources.copyFile(resources, "Package", hyts_package_name);
481 
482       String resPath = resources.toString();
483       if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\')
484           resPath = resPath.substring(1);
485 
486       try {
487 
488           URL resourceURL = new URL("file:/" + resPath + "/Package/"
489                   + hyts_package_name);
490 
491           ClassLoader cl = Support_ClassLoader.getInstance(resourceURL,
492                   getClass().getClassLoader());
493 
494           Class clazz = cl.loadClass("C");
495           assertNull("getPackage for C.class should return null",
496                   clazz.getPackage());
497 
498           clazz = cl.loadClass("a.b.C");
499           Package cPackage = clazz.getPackage();
500           assertNotNull("getPackage for a.b.C.class should not return null",
501                   cPackage);
502 
503         /*
504          * URLClassLoader doesn't work on Android for jar files
505          *
506          * URL url = getClass().getClassLoader().getResource(
507          *         packageName.replace(".", "/") + "/" + sourceJARfile);
508          *
509          * ClassLoader loader = new URLClassLoader(new URL[] { url }, null);
510          *
511          * try {
512          *     Class<?> clazz = loader.loadClass(illegalClassName);
513          *     Package pack = clazz.getPackage();
514          *     assertNull(pack);
515          * } catch(ClassNotFoundException cne) {
516          *     fail("ClassNotFoundException was thrown for " + illegalClassName);
517          * }
518         */
519       } catch(Exception e) {
520           fail("Unexpected exception was thrown: " + e.toString());
521       }
522     }
523 
524     // Android-note: Uses dalvik.system.PathClassLoader.
525     // Different behavior between cts host and run-core-test")
test_getPackageName()526     public void test_getPackageName() {
527 
528       String thisPackage = getClass().getPackageName();
529       assertEquals("libcore.java.lang", thisPackage);
530 
531       String stringPackage = String.class.getPackageName();
532       assertEquals("java.lang", stringPackage);
533 
534       String stringArrayPackage = String[].class.getPackageName();
535       assertEquals("java.lang", stringArrayPackage);
536 
537       String stringArrayArrayPackage = String[][].class.getPackageName();
538       assertEquals("java.lang", stringArrayArrayPackage);
539 
540       String intPackage = int.class.getPackageName();
541       assertEquals("java.lang", intPackage);
542 
543       String intArrayPackage = int[].class.getPackageName();
544       assertEquals("java.lang", intPackage);
545 
546       String hyts_package_name = "hyts_package_dex.jar";
547       File resources = Support_Resources.createTempFolder();
548       Support_Resources.copyFile(resources, "Package", hyts_package_name);
549 
550       String resPath = resources.toString();
551       if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\')
552           resPath = resPath.substring(1);
553 
554       try {
555 
556           URL resourceURL = new URL("file:/" + resPath + "/Package/"
557                   + hyts_package_name);
558 
559           ClassLoader cl = Support_ClassLoader.getInstance(resourceURL,
560                   getClass().getClassLoader());
561 
562           Class clazz = cl.loadClass("C");
563           assertEquals("", clazz.getPackageName());
564 
565           clazz = Class.forName("[LC;", false, cl);
566           assertEquals("", clazz.getPackageName());
567 
568           clazz = Class.forName("[[LC;", false, cl);
569           assertEquals("", clazz.getPackageName());
570 
571           clazz = cl.loadClass("a.b.C");
572           assertEquals("a.b", clazz.getPackageName());
573 
574           clazz = Class.forName("[La.b.C;", false, cl);
575           assertEquals("a.b", clazz.getPackageName());
576 
577           clazz = Class.forName("[[La.b.C;", false, cl);
578           assertEquals("a.b", clazz.getPackageName());
579       } catch(Exception e) {
580           fail("Unexpected exception was thrown: " + e.toString());
581       }
582     }
583 
test_getSigners()584     public void test_getSigners() {
585         assertNull(void.class.getSigners());
586         assertNull(PublicTestClass.class.getSigners());
587     }
588 
test_getSimpleName()589     public void test_getSimpleName() {
590         assertEquals("PublicTestClass", PublicTestClass.class.getSimpleName());
591         assertEquals("void", void.class.getSimpleName());
592         assertEquals("int[]", int[].class.getSimpleName());
593     }
594 
test_getTypeParameters()595     public void test_getTypeParameters() {
596         assertEquals(0, PublicTestClass.class.getTypeParameters().length);
597         TypeVariable [] tv = TempTestClass1.class.getTypeParameters();
598         assertEquals(1, tv.length);
599         assertEquals(Object.class, tv[0].getBounds()[0]);
600 
601         TempTestClass2<String> tc = new TempTestClass2<String>();
602         tv = tc.getClass().getTypeParameters();
603         assertEquals(1, tv.length);
604         assertEquals(String.class, tv[0].getBounds()[0]);
605     }
606 
607     class TempTestClass1<T> {
608     }
609 
610     class TempTestClass2<S extends String> extends TempTestClass1<S> {
611     }
612 
test_isAnnotation()613     public void test_isAnnotation() {
614         assertTrue(Deprecated.class.isAnnotation());
615         assertTrue(TestAnnotation.class.isAnnotation());
616         assertFalse(PublicTestClass.class.isAnnotation());
617         assertFalse(String.class.isAnnotation());
618     }
619 
test_isAnnotationPresent()620      public void test_isAnnotationPresent() {
621         assertTrue(PublicTestClass.class.isAnnotationPresent(TestAnnotation.class));
622         assertFalse(ExtendTestClass1.class.isAnnotationPresent(TestAnnotation.class));
623         assertFalse(String.class.isAnnotationPresent(Deprecated.class));
624         assertTrue(ExtendTestClass.class.isAnnotationPresent(TestAnnotation.class));
625         assertTrue(ExtendTestClass.class.isAnnotationPresent(Deprecated.class));
626      }
627 
test_isAnonymousClass()628     public void test_isAnonymousClass() {
629         assertFalse(PublicTestClass.class.isAnonymousClass());
630         assertTrue((new Thread() {}).getClass().isAnonymousClass());
631     }
632 
test_isEnum()633     public void test_isEnum() {
634       assertFalse(PublicTestClass.class.isEnum());
635       assertFalse(ExtendTestClass.class.isEnum());
636       assertTrue(TestEnum.ONE.getClass().isEnum());
637       assertTrue(TestEnum.class.isEnum());
638     }
639 
test_isLocalClass()640     public void test_isLocalClass() {
641         assertFalse(ExtendTestClass.class.isLocalClass());
642         assertFalse(TestInterface.class.isLocalClass());
643         assertFalse(TestEnum.class.isLocalClass());
644         class InternalClass {}
645         assertTrue(InternalClass.class.isLocalClass());
646     }
647 
test_isMemberClass()648     public void test_isMemberClass() {
649         assertFalse(OldClassTest.class.isMemberClass());
650         assertFalse(String.class.isMemberClass());
651         assertTrue(TestEnum.class.isMemberClass());
652         assertTrue(StaticMember$Class.class.isMemberClass());
653     }
654 
test_isSynthetic()655     public void test_isSynthetic() {
656       assertFalse("Returned true for non synthetic class.",
657               ExtendTestClass.class.isSynthetic());
658       assertFalse("Returned true for non synthetic class.",
659               TestInterface.class.isSynthetic());
660       assertFalse("Returned true for non synthetic class.",
661               String.class.isSynthetic());
662     }
663 
test_getCanonicalName()664     public void test_getCanonicalName() {
665         Class [] classArray = { int.class, int[].class, String.class,
666                                 PublicTestClass.class, TestInterface.class,
667                                 ExtendTestClass.class };
668         String [] classNames = {"int", "int[]", "java.lang.String",
669                       "libcore.java.lang.OldClassTest.PublicTestClass",
670                         "libcore.java.lang.OldClassTest.TestInterface",
671                      "libcore.java.lang.OldClassTest.ExtendTestClass"};
672 
673         for(int i = 0; i < classArray.length; i++) {
674             assertEquals(classNames[i], classArray[i].getCanonicalName());
675         }
676     }
677 
test_getClassLoader()678     public void test_getClassLoader() {
679         assertEquals(ExtendTestClass.class.getClassLoader(),
680                          PublicTestClass.class.getClassLoader());
681 
682         assertNull(int.class.getClassLoader());
683         assertNull(void.class.getClassLoader());
684     }
685 
test_getClasses()686     public void test_getClasses() {
687         assertEquals("Incorrect class array returned",
688                      11, OldClassTest.class.getClasses().length);
689     }
690 
test_getDeclaredClasses()691     public void test_getDeclaredClasses() {
692         Class [] declClasses = Object.class.getDeclaredClasses();
693         assertEquals("Incorrect length of declared classes array is returned " +
694                 "for Object.", 0, declClasses.length);
695 
696         declClasses = PublicTestClass.class.getDeclaredClasses();
697         assertEquals(2, declClasses.length);
698 
699         assertEquals(0, int.class.getDeclaredClasses().length);
700         assertEquals(0, void.class.getDeclaredClasses().length);
701 
702         for(int i = 0; i < declClasses.length; i++) {
703             Constructor<?> constr = declClasses[i].getDeclaredConstructors()[0];
704             constr.setAccessible(true);
705             PublicTestClass publicClazz = new PublicTestClass();
706             try {
707                 Object o = constr.newInstance(publicClazz);
708                 assertTrue("Returned incorrect class: " + o.toString(),
709                         o.toString().startsWith("PrivateClass"));
710             } catch(Exception e) {
711                 fail("Unexpected exception was thrown: " + e.toString());
712             }
713         }
714 
715         declClasses = TestInterface.class.getDeclaredClasses();
716         assertEquals(0, declClasses.length);
717     }
718 
test_getDeclaredConstructor$Ljava_lang_Class()719     public void test_getDeclaredConstructor$Ljava_lang_Class() throws Exception {
720         try {
721             TestClass.class.getDeclaredConstructor(String.class);
722             fail("NoSuchMethodException should be thrown.");
723         } catch(NoSuchMethodException nsme) {
724             //expected
725         }
726     }
727 
test_getDeclaredFieldLjava_lang_String()728     public void test_getDeclaredFieldLjava_lang_String() throws Exception {
729         try {
730             TestClass.class.getDeclaredField(null);
731             fail("NullPointerException is not thrown.");
732         } catch(NullPointerException npe) {
733             //expected
734         }
735 
736         try {
737             TestClass.class.getDeclaredField("NonExistentField");
738             fail("NoSuchFieldException is not thrown.");
739         } catch(NoSuchFieldException nsfe) {
740             //expected
741         }
742     }
743 
test_getDeclaredMethodLjava_lang_String$Ljava_lang_Class()744     public void test_getDeclaredMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
745         try {
746             TestClass.class.getDeclaredMethod(null, new Class[0]);
747             fail("NullPointerException is not thrown.");
748         } catch(NullPointerException npe) {
749             //expected
750         }
751 
752         try {
753             TestClass.class.getDeclaredMethod("NonExistentMethod", new Class[0]);
754             fail("NoSuchMethodException is not thrown.");
755         } catch(NoSuchMethodException nsme) {
756             //expected
757         }
758     }
759 
test_getMethodLjava_lang_String$Ljava_lang_Class()760     public void test_getMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
761         Method m = ExtendTestClass1.class.getMethod("getCount", new Class[0]);
762         assertEquals("Returned incorrect method", 0, ((Integer) (m.invoke(new ExtendTestClass1())))
763                 .intValue());
764 
765         try {
766             m = TestClass.class.getMethod("init", new Class[0]);
767             fail("Failed to throw exception accessing to init method");
768         } catch (NoSuchMethodException e) {
769             // Correct
770             return;
771         }
772 
773         try {
774             TestClass.class.getMethod("pubMethod", new Class[0]);
775             fail("NullPointerException is not thrown.");
776         } catch(NullPointerException npe) {
777             //expected
778         }
779     }
780 
test_getDeclaringClass()781     public void test_getDeclaringClass() {
782         assertEquals(OldClassTest.class, Intf1.class.getDeclaringClass());
783         assertEquals(null, Serializable.class.getDeclaringClass());
784         assertEquals(null, OldClassTest.class.getDeclaringClass());
785 
786         assertEquals(OldClassTest.class, PublicTestClass.class.getDeclaringClass());
787 
788         // https://code.google.com/p/android/issues/detail?id=61003
789         assertEquals(null, new Object() {}.getClass().getDeclaringClass());
790         assertEquals(null, new AnonymousMemberFixture().instanceOfAnonymousClass.getClass().getDeclaringClass());
791 
792         // Arrays, primitive types, and void all return null.
793         assertEquals(null, char[].class.getDeclaringClass());
794         assertEquals(null, int.class.getDeclaringClass());
795         assertEquals(null, void.class.getDeclaringClass());
796     }
797 
test_getFieldLjava_lang_String()798     public void test_getFieldLjava_lang_String() throws Exception {
799         Field f = TestClass.class.getField("pubField");
800         assertEquals("Returned incorrect field", 2, f.getInt(new TestClass()));
801 
802         f = PublicTestClass.class.getField("TEST_FIELD");
803         assertEquals("Returned incorrect field", "test field",
804                 f.get(new PublicTestClass()));
805 
806         f = PublicTestClass.class.getField("TEST_INTERFACE_FIELD");
807         assertEquals("Returned incorrect field", 0,
808                 f.getInt(new PublicTestClass()));
809 
810         try {
811             TestClass.class.getField(null);
812             fail("NullPointerException is thrown.");
813         } catch(NullPointerException npe) {
814             //expected
815         }
816     }
817 
test_getFields2()818     public void test_getFields2() throws Exception {
819         Field[] f;
820         Field expected = null;
821 
822         f = PublicTestClass.class.getFields();
823         assertEquals("Test 1: Incorrect number of fields;", 2, f.length);
824 
825         f = Cls2.class.getFields();
826         assertEquals("Test 2: Incorrect number of fields;", 6, f.length);
827 
828         f = Cls3.class.getFields();
829         assertEquals("Test 2: Incorrect number of fields;", 5, f.length);
830 
831         for (Field field : f) {
832             if (field.toString().equals("public static final int "
833                     + "libcore.java.lang.OldClassTest$Intf3.field1")) {
834                 expected = field;
835                 break;
836             }
837         }
838         if (expected == null) {
839             fail("Test 3: getFields() did not return all fields.");
840         }
841         assertEquals("Test 4: Incorrect field;", expected,
842                 Cls3.class.getField("field1"));
843 
844         expected = null;
845         for (Field field : f) {
846             if(field.toString().equals("public static final int " +
847                     "libcore.java.lang.OldClassTest$Intf1.field2")) {
848                 expected = field;
849                 break;
850             }
851         }
852         if (expected == null) {
853             fail("Test 5: getFields() did not return all fields.");
854         }
855         assertEquals("Test 6: Incorrect field;", expected,
856                 Cls3.class.getField("field2"));
857     }
858 
test_getFields()859     public void test_getFields() throws Exception {
860         Field expected = null;
861         Field[] fields = Cls2.class.getFields();
862         for (Field field : fields) {
863             if(field.toString().equals("public int libcore.java.lang.OldClassTest$Cls2.field1")) {
864                 expected = field;
865                 break;
866             }
867         }
868         if (expected == null) {
869             fail("getFields() did not return all fields");
870         }
871         assertEquals(expected, Cls2.class.getField("field1"));
872     }
873 
test_getInterfaces()874     public void test_getInterfaces() {
875         Class [] interfaces1 = Cls1.class.getInterfaces();
876         assertEquals(1, interfaces1.length);
877         assertEquals(Intf2.class, interfaces1[0]);
878 
879         Class [] interfaces2 = Cls2.class.getInterfaces();
880         assertEquals(1, interfaces2.length);
881         assertEquals(Intf1.class, interfaces2[0]);
882 
883         Class [] interfaces3 = Cls3.class.getInterfaces();
884         assertEquals(2, interfaces3.length);
885         assertEquals(Intf3.class, interfaces3[0]);
886         assertEquals(Intf4.class, interfaces3[1]);
887 
888         Class [] interfaces4 = Cls4.class.getInterfaces();
889         assertEquals(0, interfaces4.length);
890     }
891 
test_getMethods()892     public void test_getMethods() throws Exception {
893         assertEquals("Incorrect number of methods", 10,
894                 Cls2.class.getMethods().length);
895         assertEquals("Incorrect number of methods", 11,
896                 Cls3.class.getMethods().length);
897 
898         Method expected = null;
899         Method[] methods = Cls2.class.getMethods();
900         for (Method method : methods) {
901             if(method.toString().equals("public void libcore.java.lang.OldClassTest$Cls2.test()")) {
902                 expected = method;
903                 break;
904             }
905         }
906         if (expected == null) {
907             fail("getMethods() did not return all methods");
908         }
909         assertEquals(expected, Cls2.class.getMethod("test"));
910 
911         expected = null;
912         methods = Cls3.class.getMethods();
913         for (Method method : methods) {
914             if(method.toString().equals("public void libcore.java.lang.OldClassTest$Cls3.test()")) {
915                 expected = method;
916                 break;
917             }
918         }
919         if (expected == null) {
920             fail("getMethods() did not return all methods");
921         }
922         assertEquals(expected, Cls3.class.getMethod("test"));
923 
924         expected = null;
925         methods = Cls3.class.getMethods();
926         for (Method method : methods) {
927             if(method.toString().equals("public void libcore.java.lang.OldClassTest$Cls3.test2(int,"
928                     + "java.lang.Object)")) {
929                 expected = method;
930                 break;
931             }
932         }
933         if (expected == null) {
934             fail("getMethods() did not return all methods");
935         }
936 
937         assertEquals(expected, Cls3.class.getMethod("test2", int.class,
938                 Object.class));
939 
940         assertEquals("Incorrect number of methods", 1,
941                 Intf5.class.getMethods().length);
942     }
943 
test_getResourceLjava_lang_String()944     public void test_getResourceLjava_lang_String() {
945         assertNull(getClass().getResource(
946                 "libcore/java/lang/NonExistentResource"));
947         assertNull(getClass().getResource(getClass().getName() + "NonExistentResource"));
948     }
949 
test_getResourceAsStreamLjava_lang_String()950     public void test_getResourceAsStreamLjava_lang_String() throws Exception {
951         String name = "/HelloWorld.txt";
952         assertNotNull("the file " + name + " can not be found in this " +
953                 "directory", getClass().getResourceAsStream(name));
954 
955         final String nameBadURI = "org/apache/harmony/luni/tests/test_resource.txt";
956         assertNull("the file " + nameBadURI + " should not be found in this directory",
957                 getClass().getResourceAsStream(nameBadURI));
958 
959         ClassLoader pcl = getClass().getClassLoader();
960         Class<?> clazz = pcl.loadClass("libcore.java.lang.OldClassTest");
961         assertNotNull(clazz.getResourceAsStream("HelloWorld1.txt"));
962 
963         try {
964             getClass().getResourceAsStream(null);
965             fail("NullPointerException is not thrown.");
966         } catch(NullPointerException npe) {
967             //expected
968         }
969     }
970 
test_isAssignableFromLjava_lang_Class()971     public void test_isAssignableFromLjava_lang_Class() {
972         assertFalse("returned true not assignable classes",
973                 Integer.class.isAssignableFrom(String.class));
974 
975         try {
976             Runnable.class.isAssignableFrom(null);
977             fail("NullPointerException is not thrown.");
978         } catch(NullPointerException npe) {
979             //expected
980         }
981     }
982 
test_newInstance()983     public void test_newInstance() throws Exception {
984         try {
985             TestClass3.class.newInstance();
986             fail("IllegalAccessException is not thrown.");
987         } catch(IllegalAccessException  iae) {
988             //expected
989         }
990 
991         try {
992             TestClass1C.class.newInstance();
993             fail("ExceptionInInitializerError should be thrown.");
994         } catch (java.lang.ExceptionInInitializerError ie) {
995             //expected
996         }
997     }
998 
test_asSubclass1()999     public void test_asSubclass1() {
1000         assertEquals(ExtendTestClass.class,
1001                 ExtendTestClass.class.asSubclass(PublicTestClass.class));
1002 
1003         assertEquals(PublicTestClass.class,
1004                 PublicTestClass.class.asSubclass(TestInterface.class));
1005 
1006         assertEquals(ExtendTestClass1.class,
1007                 ExtendTestClass1.class.asSubclass(PublicTestClass.class));
1008 
1009         assertEquals(PublicTestClass.class,
1010                 PublicTestClass.class.asSubclass(PublicTestClass.class));
1011     }
1012 
test_asSubclass2()1013     public void test_asSubclass2() {
1014         try {
1015             PublicTestClass.class.asSubclass(ExtendTestClass.class);
1016             fail("Test 1: ClassCastException expected.");
1017         } catch(ClassCastException cce) {
1018             // Expected.
1019         }
1020 
1021         try {
1022             PublicTestClass.class.asSubclass(String.class);
1023             fail("Test 2: ClassCastException expected.");
1024         } catch(ClassCastException cce) {
1025             // Expected.
1026         }
1027     }
1028 
test_cast()1029     public void test_cast() {
1030         Object o = PublicTestClass.class.cast(new ExtendTestClass());
1031         assertTrue(o instanceof ExtendTestClass);
1032 
1033         try {
1034             ExtendTestClass.class.cast(new PublicTestClass());
1035             fail("Test 1: ClassCastException expected.");
1036         } catch(ClassCastException cce) {
1037             //expected
1038         }
1039 
1040         try {
1041             ExtendTestClass.class.cast(new String());
1042             fail("ClassCastException is not thrown.");
1043         } catch(ClassCastException cce) {
1044             //expected
1045         }
1046     }
1047 
test_desiredAssertionStatus()1048     public void test_desiredAssertionStatus() {
1049       Class [] classArray = { Object.class, Integer.class,
1050                               String.class, PublicTestClass.class,
1051                               ExtendTestClass.class, ExtendTestClass1.class};
1052 
1053       for(int i = 0; i < classArray.length; i++) {
1054           assertFalse("assertion status for " + classArray[i],
1055                        classArray[i].desiredAssertionStatus());
1056       }
1057    }
1058 
testGetResourceAsStream1()1059     public void testGetResourceAsStream1() throws IOException {
1060         Class clazz = getClass();
1061 
1062         InputStream stream = clazz.getResourceAsStream("HelloWorld.txt");
1063         assertNotNull(stream);
1064 
1065         byte[] buffer = new byte[20];
1066         int length = stream.read(buffer);
1067         String s = new String(buffer, 0, length);
1068         assertEquals("Hello, World.\n",  s);
1069 
1070         stream.close();
1071     }
1072 
testGetResourceAsStream2()1073     public void testGetResourceAsStream2() throws IOException {
1074         Class clazz = getClass();
1075 
1076         InputStream stream = clazz.getResourceAsStream("/libcore/java/lang/HelloWorld.txt");
1077         assertNotNull(stream);
1078 
1079         byte[] buffer = new byte[20];
1080         int length = stream.read(buffer);
1081         String s = new String(buffer, 0, length);
1082         assertEquals("Hello, World.\n", s);
1083 
1084         stream.close();
1085 
1086         try {
1087             clazz.getResourceAsStream(null);
1088             fail("NullPointerException is not thrown.");
1089         } catch(NullPointerException npe) {
1090             //expected
1091         }
1092         assertNull(clazz.getResourceAsStream("/NonExistentResource"));
1093         assertNull(clazz.getResourceAsStream("libcore/java/lang/HelloWorld.txt"));
1094     }
1095 }
1096 
1097 class AnonymousMemberFixture {
1098     Object instanceOfAnonymousClass = new Object() {};
1099 }
1100