Skip to content

Instantly share code, notes, and snippets.

@ZenLiuCN
Created October 21, 2021 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZenLiuCN/bfb2283101b375979ae900dfda8db552 to your computer and use it in GitHub Desktop.
Save ZenLiuCN/bfb2283101b375979ae900dfda8db552 to your computer and use it in GitHub Desktop.
public interface ClassSerialize{
static String classToString(Class cls) {
return cls.getName()
.replaceFirst("class ", "")
.replaceFirst("interface ", "");
}
@SneakyThrows
static Class stringToClass(String cls) {
if (cls.contains("$")) {
val outer = cls.substring(0, cls.indexOf('$'));
val inner = Seq.of(cls.substring(cls.indexOf('$')).split("\\$")).filter(x -> !x.isEmpty()).toList();
val out = Class.forName(outer);
var last = out;
var find = out;
for (String s : inner) {
for (Class<?> ac : find.getClasses()) {
if (ac.getSimpleName().equals(s)) {
find = ac;
break;
}
}
if (last == find) {
throw new ClassNotFoundException("not found " + s + " in " + find.getName());
}
last = find;
}
}
return Class.forName(cls);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment