1 /*
2  * Copyright (C) 2019 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.tools.layoutlib.create;
18 
19 import java.util.HashSet;
20 import java.util.Map;
21 
22 import com.google.common.collect.ImmutableMap;
23 
24 class TestClassLoader extends ClassLoader {
25     private final Map<String, byte[]> mClassDefinitions;
26     private final HashSet<String> mLoadedClasses = new HashSet<>();
27 
TestClassLoader(Map<String, byte[]> classDefinitions)28     private TestClassLoader(Map<String, byte[]> classDefinitions) {
29         mClassDefinitions = classDefinitions;
30     }
31 
TestClassLoader(String name, byte[] bytes)32     TestClassLoader(String name, byte[] bytes) {
33         this(ImmutableMap.of(name, bytes));
34     }
35 
wasClassLoaded(String name)36     public boolean wasClassLoaded(String name) {
37         return mLoadedClasses.contains(name);
38     }
39 
40     @Override
findClass(String name)41     protected Class<?> findClass(String name) throws ClassNotFoundException {
42         byte[] classContent = mClassDefinitions.get(name);
43         if (classContent != null) {
44             mLoadedClasses.add(name);
45             return defineClass(name, classContent, 0, classContent.length);
46         }
47         return super.findClass(name);
48     }
49 }
50