java如何用反射获取类实例
想了解更多Java相关,百度搜索圈T社区,免费视频教程。纯干货
public class Demo {private String key1 = "1";private String key2 = "2";public String getKey1() {return key1;}public void setKey1(String key1) {this.key1 = key1;}public String getKey2() {return key2;}public void setKey2(String key2) {this.key2 = key2;}public static void main(String[] args) throws Exception {//参数 “Demo” 是类的全名,如果在包结构下,要有完整包路径 比如: com.test.DemoClass<?> clazz = Class.forName("Demo");//“Demo”类必须有默认构造方法,否则会抛出异常Demo demo = (Demo) clazz.newInstance();System.out.println(demo.getKey1());System.out.println(demo.getKey2());}}
调用运行时类本身的.class属性
Class clazz=Person.class;
//创建class对应的运行时类Person对象
System.out.println(clazz);
Class clazz1=String.class;
System.out.println(clazz1);
运行时类的对象获取
Person p=new Person();
Class clazz2=p.getClass();
System.out.println(clazz2);
通过Class的静态方法获取
String className="test.Person";
Class clazz3=Class.forName(className);
System.out.println(clazz3);
通过类的加载器
ClassLoader classLoader=this.getClass().getClassLoader();
Class clazz4=classLoader.loadClass(className);
System.out.println(clazz4);
java定义一个动物类,用构造方法实现动物的实例化
public class Animal{ int height;//身高 int weight;//体重 int age;//年龄 String sex;//性别 public Animal(int height,int weight,int age,String sex){//带4个参数的构造方法 this.height = height; this.weight= weight; this.age= age; this.sex= sex;
}public static void main(String[] args) { Animal animal = new Animal(100,60,2,"雄性")
;/*animal这个对象就具有height、weight、age、sex属性值了*/}}

