十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
Class clazz = Student.class; // 访问Student类的class属性
Student stu = new Student();
Class clazz = stu.getClass(); // 调用Student对象的getName方法
有哪些方式可以提高反射效率?
专注于为中小企业提供成都网站设计、成都做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业全州免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了近千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
// 1. 没有缓存
void createInstance(String className){
return Class.forName(className).newInstance();
}
// 2. 缓存forName的结果
void createInstance(String className){
cachedClass = cache.get(className);
if (cachedClass == null){
cachedClass = Class.forName(className);
cache.set(className, cachedClass);
}
return cachedClass.newInstance();
}
如何防止反射序列化***单例
public enum Singleton {
INSTANCE {
@Override
protected void read() {
System.out.println("read");
}
@Override
protected void write() {
System.out.println("write");
}
};
protected abstract void read();
protected abstract void write();
}
class文件:
public abstract class Singleton extends Enum{
private Singleton(String s, int i){
super(s, i);
}
protected abstract void read();
protected abstract void write();
public static Singleton[] values(){
Singleton asingleton[];
int i;
Singleton asingleton1[];
System.arraycopy(asingleton = ENUM$VALUES, 0, asingleton1 = new Singleton[i = asingleton.length], 0, i);
return asingleton1;
}
public static Singleton valueOf(String s) {
return (Singleton)Enum.valueOf(singleton/Singleton, s);
}
Singleton(String s, int i, Singleton singleton){
this(s, i);
}
public static final Singleton INSTANCE;
private static final Singleton ENUM$VALUES[];
static {
INSTANCE = new Singleton("INSTANCE", 0){
protected void read(){
System.out.println("read");
}
protected void write(){
System.out.println("write");
}
};
ENUM$VALUES = (new Singleton[] {
INSTANCE
});
}
}
//readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
通过反射获得泛型的实际类型参数
例子:
public class GenericTest {
public static void main(String[] args) throws Exception {
getParamType();
}
/*利用反射获取方法参数的实际参数类型*/
public static void getParamType() throws NoSuchMethodException{
Method method = GenericTest.class.getMethod("applyMap",Map.class);
//获取方法的泛型参数的类型
Type[] types = method.getGenericParameterTypes();
System.out.println(types[0]);
//参数化的类型
ParameterizedType pType = (ParameterizedType)types[0];
//原始类型
System.out.println(pType.getRawType());
//实际类型参数
System.out.println(pType.getActualTypeArguments()[0]);
System.out.println(pType.getActualTypeArguments()[1]);
}
/*供测试参数类型的方法*/
public static void applyMap(Map map){
}
}
java.util.Map
interface java.util.Map
class java.lang.Integer
class java.lang.String