正如其他人所说,如果您打算静态访问该方法,则不需要实例,因此根本不需要参数TestClass#getName
。但是,如果您确实希望它成为实例方法,则可以执行以下三件事之一:
TestClassTwo
1)输入 类型TestClass#getName
:
public class TestClass {
public void getName(TestClassTwo obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String name = obj.getTwoName();
// Do something with 'name'
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
TestClass tc=new TestClass();
tc.getName(new TestClassTwo());
}
}
2) 将对象转换为 的实例 TestClassTwo
,检查类型:
public class TestClass {
public void getName(Object obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
if (obj instanceof TestClassTwo) {
TestClassTwo two = (TestClassTwo) obj;
String name = two.getTwoName();
// Do something with 'name'
} else {
// Handle failure accordingly (throw an exception, log an error, do nothing, etc.)
}
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
TestClass tc=new TestClass();
tc.getName(new TestClassTwo());
}
}
3)如果你想允许其他类有一个 getTwoName()
功能,定义一个接口并将该接口的一个实例作为参数 TestClass#getName
:
public interface HasTwoName {
public String getTwoName();
}
public class TestClassTwo implements HasTwoName {
@Override
public String getTwoName() {
return "2nd";
}
}
public class TestClass {
public void getName(HasTwoName obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
String name = two.getTwoName();
// Do something with 'name'
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
TestClass tc=new TestClass();
tc.getName(new TestClassTwo());
}
}