老师请检查
来源:2-9 自由编程
慕工程8205364
2021-06-03 17:54:19
package com.imooc.reflect.zy1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class GetDeclaredSample {
public static void main(String[] args) {
try {
Class bookClass = Class.forName("com.imooc.reflect.zy1.Book");
Constructor constructor = bookClass.getConstructor(new Class[]{
Integer.class, String.class, Float.class
});
Book book = (Book) constructor.newInstance(new Object[]{
1010, "三国志", 28.0f
});
Field[] fields = bookClass.getDeclaredFields();
for (Field field : fields) {
if (field.getModifiers() == 1) {
Object o = field.get(book);
System.out.println(o);
} else if (field.getModifiers() == 2) {
String ffm = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
Method method = bookClass.getMethod(ffm);
Object invoke = method.invoke(book);
System.out.println(invoke);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
package com.imooc.reflect.zy1;
public class Book {
private Integer id;
private String name;
public Float price;
public Book() {
}
public Book(Integer id, String name, Float price) {
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
1回答
同学你好,同学的代码完成的不错,很棒,继续加油~
祝学习愉快!
相似问题