Class<Student> clazz = Student.class; // 访问Student类的class属性
Student stu = new Student();
Class<Student> 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<Integer,String> map){
}
}
java.util.Map<java.lang.Integer, java.lang.String>
interface java.util.Map
class java.lang.Integer
class java.lang.String
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。