This repository has been archived by the owner on Feb 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
ParkJeongHwan
committed
Sep 23, 2019
1 parent
11545f2
commit 464f223
Showing
2 changed files
with
38 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 37 additions & 6 deletions
43
src/main/java/com/realtimetech/reflection/classloader/ClassDynamicLoader.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,50 @@ | ||
package com.realtimetech.reflection.classloader; | ||
|
||
import java.util.HashMap; | ||
|
||
import com.realtimetech.reflection.classfile.classfile.ClassFile; | ||
|
||
public class ClassDynamicLoader extends ClassLoader { | ||
public ClassDynamicLoader() { | ||
super(null); | ||
} | ||
private HashMap<String, byte[]> classMap; | ||
|
||
public ClassDynamicLoader(Class<?> baseClass) { | ||
super(baseClass.getClassLoader()); | ||
public ClassDynamicLoader() { | ||
this(null); | ||
} | ||
|
||
public ClassDynamicLoader(ClassLoader classLoader) { | ||
super(classLoader); | ||
this.classMap = new HashMap<String, byte[]>(); | ||
} | ||
|
||
public void addClass(String className, byte[] bytes) { | ||
this.classMap.put(className, bytes); | ||
} | ||
|
||
public void addClassFile(ClassFile className) { | ||
this.classMap.put(className.getName(), className.getBytes()); | ||
} | ||
|
||
@Override | ||
protected Class<?> findClass(String name) throws ClassNotFoundException { | ||
Class<?> result = null; | ||
try { | ||
result = super.findClass(name); | ||
} catch (ClassNotFoundException e) { | ||
if (this.classMap.containsKey(name)) { | ||
byte[] bytes = this.classMap.get(name); | ||
this.classMap.remove(name); | ||
result = defineClass(name, bytes, 0, bytes.length); | ||
} | ||
} | ||
|
||
if (result == null) { | ||
throw new ClassNotFoundException(); | ||
} | ||
|
||
return result; | ||
} | ||
|
||
public Class<?> loadClassByBytes(byte[] bytes, String className) { | ||
public Class<?> loadClassByBytes(String className, byte[] bytes) { | ||
return defineClass(className, bytes, 0, bytes.length); | ||
} | ||
} |