摘要: 本文主要探讨在 Java 编程环境中从 Object 对象中获取值(value)的不同方法。在 Java 中,Object 是所有类的父类,经常会遇到需要从各种类型的对象中提取特定数据值的情况。通过对不同数据结构和对象类型的分析,阐述如何有效地获取其中包含的关键信息。
一、引言
二、基本对象属性获取
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Person person = new Person("John", 25);
String nameValue = person.getName();
int ageValue = person.getAge();
三、集合中对象的值获取
import java.util.ArrayList;
class Product {
private String productName;
private double price;
public Product(String productName, double price) {
this.productName = productName;
this.price = price;
}
public String getProductName() {
return productName;
}
public double getPrice() {
return price;
}
}
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<Product> productList = new ArrayList<>();
productList.add(new Product("Book", 19.99));
productList.add(new Product("Pen", 0.99));
for (Product product : productList) {
String productName = product.getProductName();
double price = product.getPrice();
System.out.println("Product: " + productName + ", Price: " + price);
}
}
}
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 3);
Integer valueOfApple = map.get("apple");
Integer valueOfBanana = map.get("banana");
}
}
四、通过反射获取对象的值
import java.lang.reflect.Field;
class Student {
private String studentName;
private int studentId;
public Student(String studentName, int studentId) {
this.studentName = studentName;
this.studentId = studentId;
}
}
public class ReflectionExample {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Student student = new Student("Alice", 101);
Class<?> studentClass = student.getClass();
Field studentNameField = studentClass.getDeclaredField("studentName");
studentNameField.setAccessible(true);
String studentNameValue = (String) studentNameField.get(student);
Field studentIdField = studentClass.getDeclaredField("studentId");
studentIdField.setAccessible(true);
int studentIdValue = studentIdField.getInt(student);
}
}