本笔记来源于:尚硅谷Java零基础全套视频教程(宋红康2023版,java入门自学必备)
b站视频
调用指定的属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Test public void testField1() throws Exception { Class clazz = Person.class;
Person p = (Person) clazz.newInstance();
Field name = clazz.getDeclaredField("name");
name.setAccessible(true); name.set(p,"Tom");
System.out.println(name.get(p)); }
|
调用指定的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @Test public void testMethod() throws Exception {
Class clazz = Person.class;
Person p = (Person) clazz.newInstance();
Method show = clazz.getDeclaredMethod("show", String.class); show.setAccessible(true);
Object returnValue = show.invoke(p,"CHN"); System.out.println(returnValue);
System.out.println("*************如何调用静态方法*****************");
Method showDesc = clazz.getDeclaredMethod("showDesc"); showDesc.setAccessible(true);
Object returnVal = showDesc.invoke(Person.class); System.out.println(returnVal); }
|
调用指定的构造器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Test public void testConstructor() throws Exception { Class clazz = Person.class;
Constructor constructor = clazz.getDeclaredConstructor(String.class);
constructor.setAccessible(true);
Person per = (Person) constructor.newInstance("Tom"); System.out.println(per); }
|