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();
}
複製代碼
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
複製代碼