Java如何在一个类中引用另一个类的成员变量和方法

不希望使用内部类来做,有听老师说过用构造函数的方法,不过还是不太清楚,希望举例解释下~

第1个回答  推荐于2017-10-11
public class Student(){
String id;
String name;

public Student(){}
public Student(String id,String name){
this.id = id;
this.name = name;
}
}
====
public class Test(){
String ids;
String names;

public static void main(String[] args){
Test test = new Test();
Student stu = new Student("001","jack");
test.ids = stu.id;
test.nams = stu.name;
System.out.println("ID=" + this.ids + " Name=" + this.names);
}
}本回答被提问者采纳
第2个回答  2009-10-06
利用反射机制访问类的成员变量

//获得指定变量的值
public static Object getValue(Object instance, String fieldName)
throws IllegalAccessException, NoSuchFieldException {

Field field = getField(instance.getClass(), fieldName);
// 参数值为true,禁用访问控制检查
field.setAccessible(true);
return field.get(instance);
}

//该方法实现根据变量名获得该变量的值
public static Field getField(Class thisClass, String fieldName)
throws NoSuchFieldException {

if (thisClass == null) {
throw new NoSuchFieldException("Error field !");
}
}

这种访问方式能够访问到私有成员变量!
第3个回答  2009-10-06
将被引用类实例化,通过实例引用,或者将要引用的类成员定义为static成员
第4个回答  2009-10-06
把那个类的成员变量和方法设为public或静态
相似回答