您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。