1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.xsdc.tests;
18 
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 
23 class TestCompilationResult {
24     private static class ByteArrayClassLoader extends ClassLoader {
25         private Map<String, byte[]> codeMap;
26 
ByteArrayClassLoader(List<TestHelper.InMemoryJavaClassObject> objects)27         ByteArrayClassLoader(List<TestHelper.InMemoryJavaClassObject> objects) {
28             super();
29             codeMap = new HashMap<>();
30             for (TestHelper.InMemoryJavaClassObject object : objects) {
31                 codeMap.put(object.getClassName(), object.getBytes());
32             }
33         }
34 
35         @Override
findClass(String name)36         protected Class findClass(String name) throws ClassNotFoundException {
37             byte[] code = codeMap.get(name);
38             return defineClass(name, code, 0, code.length);
39         }
40     }
41 
42     private Map<String, Class<?>> classes;
43 
TestCompilationResult(List<TestHelper.InMemoryJavaClassObject> objects)44     TestCompilationResult(List<TestHelper.InMemoryJavaClassObject> objects)
45             throws ClassNotFoundException {
46         ByteArrayClassLoader loader = new ByteArrayClassLoader(objects);
47         classes = new HashMap<>();
48 
49         for (TestHelper.InMemoryJavaClassObject object : objects) {
50             Class<?> cls = loader.loadClass(object.getClassName());
51             classes.put(object.getClassName(), cls);
52         }
53     }
54 
loadClass(String name)55     Class<?> loadClass(String name) {
56         return classes.get(TestHelper.packageName + "." + name);
57     }
58 }
59