求讲解,老师
方法改为 private 怎么调用?
方法改为 private 怎么调用?
2017-10-15
public class Student { private String stuno; private String name; private float math; private float english; private float computer; public Student() { } public Student(String stuno,String name,float math,float english,float computer) { this.setStuno(stuno); this.setName(name); this.setMath(math); this.setEnglish(english); this.setComputer(computer); } public void setStuno(String s) { stuno = s; } public void setName(String n) { name = n; } public void setMath(float m) { math = m; } public void setEnglish(float e) { english = e; } public void setComputer(float c) { computer = c; } public String getStuno() { return stuno; } public String getName() { return name; } public float getMath() { return math; } public float getEnglish() { return english; } public float getComputer() { return computer; } public float sum() { return math+english+computer; } public float avg() { return this.sum()/3; } public float max() { float max = math; max = max > computer?max:computer; max=max>english?max:english; return max; } public float min() { float max = math; max = max < computer?max:computer; max=max<english?max:english; return max; }};
Java调用private方法利用的是Java中的类反射机制 。
定义一个class,定义一个内部private方法:
public class PrivateTest {
private void print() {
System.out.println("this is a private method");
}
}
再定义一个class去访问刚才定义的private方法,也就是print()如下
import java.lang.reflect.Method;
public class PrivateTest2 {
public static void main(String[] args) {
try {
Method method = PrivateTest.class.getDeclaredMethod("print", new Class[]{});
method.setAccessible(true);
Method.invoke(new PrivateTest(), new Object[] {});
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
利用java的反射机制,即使是private方法,也可以被调用使用。
举报