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