com.github.yoojia.halo.utils.Classes Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of halo-core Show documentation
Show all versions of halo-core Show documentation
A FAST && THIN && HIGH SCALABLE Java web framework
package com.github.yoojia.halo.utils;
import com.github.yoojia.halo.HaloRequest;
import com.github.yoojia.halo.HaloResponse;
import java.lang.reflect.Method;
/**
* @author YOOJIA.CHEN ([email protected])
*/
public final class Classes {
private final ClassLoader mClassLoader;
public Classes() {
mClassLoader = Thread.currentThread().getContextClassLoader();
}
public Class> safetyLoad(String className){
try {
return mClassLoader.loadClass(className);
} catch (Exception e) {
return null;
}
}
public void checkConstructor(Class> clazz, String name){
try {
clazz.getConstructor(); // 在自动生成对象时,需要一个无参数构造方法
} catch (NoSuchMethodException e) {
throw new RuntimeException("A " + name + " MUST has a public NON-PARAMS constructor !", e);
}
}
public T newClassByName(String className){
// 为内建模块class缩写恢复原类名
if( ! className.contains(".")) {
className = "com.github.yoojia.halo." + className;
}
try {
@SuppressWarnings("unchecked")
final Class clazz = (Class) mClassLoader.loadClass(className);
return clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot instance class: " + className, e);
}
}
public boolean isHaloMethod(Method method){
final Class>[] types = method.getParameterTypes();
if(types.length < 2){
return false;
}
boolean req = false, res = false;
for (Class> type : types) {
req |= HaloRequest.class.equals(type);
res |= HaloResponse.class.equals(type);
}
return req && res;
}
}