Student stu
=new Student();
Class
<?> c
= Class
.forName("test.Student");
Constructor
<?> ca
= c
.getConstructor();
ca
.newInstance();
三种方式获得类对象
1.类名
.class.newinstace
:来获得无参的方法
Student stu
= Student
.class.newInstance();
2.对象名
.getclass
Student stu
=new Student();
Class
<? extends Student> c
= stu
.getClass();
Field f
= c
.getField("sid");
Field f
= c
.getDeclaredField("sid");
System
.out
.println(f
);
System
.out
.println(f
.getName());
System
.out
.println(f
.getType());
System
.out
.println(f
.getModifiers());
3class
.formName(全险定名
)
Class
<?> c
= Class
.forName("test.Student");
Object obj
= c
.newInstance();
Student stu
=(Student
)obj
;
实例化类对象
c
.newInstance();
获取该指定对象的属性
Field f
= c
.getDeclaredField("sid");
得到属性名
System
.out
.println(f
.getName());
System
.out
.println(f
.getType());
System
.out
.println(f
.getModifiers());
Field
[] fs
= c
.getDeclaredFields();
for (Field f
: fs
) {
System
.out
.println(f
.getName());
System
.out
.println(f
.getType());
System
.out
.println(f
.getModifiers());
}
Class
<?> c
= Class
.forName("test.Student");
Constructor
<?> cs
= c
.getConstructor(String
.class);
Object stu
= cs
.newInstance("soo1");
Field f
= c
.getDeclaredField("sid");
f
.setAccessible(true);
System
.out
.println(f
.get(stu
));
Constructor
<?> cq
= c
.getDeclaredConstructor(Integer
.class);
Field ff
= c
.getDeclaredField("age");
cq
.setAccessible(true);
Object sq
= cq
.newInstance(17);
System
.out
.println(ff
.get(sq
));
Class
<?> c
= Class
.forName("test.Student");
Constructor
<?> cs
= c
.getDeclaredConstructor(String
.class,String
.class);
Object obj
= cs
.newInstance("s002","zs");
Field
[] fi
= c
.getDeclaredFields();
for (Field f
: fi
) {
f
.setAccessible(true);
System
.out
.println(f
.get(obj
));
}
Class
<?> c
= Class
.forName("test.Student");
Object obj
= c
.newInstance();
Method m
= c
.getMethod("hello");
m
.invoke(obj
);
Class
<?> c
= Class
.forName("test.Student");
Object obj
= c
.newInstance();
Method m
= c
.getDeclaredMethod("add",Integer
.class,Integer
.class);
m
.setAccessible(true);
System
.out
.println(m
.invoke(obj
, 1,2));
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-29674.html