反射之类的加载器
@Test
public void test1(){
//对于自定义类,使用系统类加载器进行加载
ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
System.out.println(classLoader);//系统的加载器
//调用系统类加载器的getParent():获取扩展类加载器
ClassLoader classLoader1 = classLoader.getParent();
System.out.println(classLoader1);//扩展类加载器
//调用扩展类加载器的getParent():无法获取引导类加载器
//引导类加载器主要负责加载java的核心类库,无法加载自定义类的。
ClassLoader classLoader2 = classLoader1.getParent();
System.out.println(classLoader2);//引导类加载器,不能拿到
ClassLoader loader = String.class.getClassLoader();
System.out.println(loader);//引导类加载器,不能拿到
}
/*
Properties:用来读取配置文件。
*/
@Test
public void test2() throws Exception {
Properties pros = new Properties();
//此时的文件默认在当前的module下
//读取配置文件的方式一:
// FileInputStream fis = new FileInputStream("src\\jdbc1.properties");
// pros.load(fis);
//读取配置文件的方式二:
//配置文件默认识别为当前module下的src下
// ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
// InputStream ips = classLoader.getResourceAsStream("jdbc1.properties");
// pros.load(ips);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
System.out.println("user=" + user + ",password=" + password );
}
反射的动态性的体会
@Test
public void test2(){
for(int i = 0;i < 100;i++){
int num = new Random().nextInt(3);//0,1,2
String classPath = "";
switch(num){
case 0:
classPath = "java.util.Date";
break;
case 1:
classPath = "java.lang.Object";
break;
case 2:
classPath = "com.atguigu.java.Person";
break;
}
try {
Object obj = getInstance(classPath);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
创建一个指定类的对象。
classPath:指定类的全类名
*/
public Object getInstance(String classPath) throws Exception {
Class clazz = Class.forName(classPath);
return clazz.newInstance();
}
Person类
public class Person {
private String name;
public int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person() {
System.out.println("无参构造器");
}
private Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void show(){
System.out.println("hello i am people");
}
private String showNation(String nation){
System.out.println("i am from " + nation);
return nation;
}
}
标签:反射,String,age,println,之类,加载,public,name
From: https://www.cnblogs.com/blwx/p/16742710.html