[英]How do I allow a function parameter to take on various objects types?
我希望能够将任何对象传递给searchO
方法,例如td1.searchO("akash")
或td1.searchO(1)
。 它应该接受所有对象,因为对象类是所有对象的超类。
我该怎么做?
public boolean searchO(String o ) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Statement st=null;
Connection con=test1.getConnection();
st=con.createStatement();
ResultSet rs=st.executeQuery("select * from `student` where `fname` = '" + o + "' ;");
//System.out.println("full name is "+rs.getString("lname")+" "+rs.getString("fname"));
if(rs.next()==true){
System.out.println("full name is "+rs.getString("lname")+" "+rs.getString("fname"));
return true;
}
else{
return false;
}
}
您可能对使用重载感兴趣。
您将有两种方法。
public boolean searchO(int o ) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
return searchO(String.valueOf(o));
}
public boolean searchO(String o ) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
//same no changes as in your original code
}
安全说明:您的SQL查询容易受到SQL注入的攻击。 为了避免这种威胁,请使用PreparedStatement 。 请记住,切勿将变量的值连接到任何查询字符串。
由于您将您的参数用作字符串过滤器(假设fname
是具有varchar / text类型的db列),因此更可取的是将类型保留为String
您可能会认为将参数类型更改为public boolean searchO(Object o )
并调用o.toString()
可以解决问题,但是如果稍后您传递没有适当toString()
实现的类型,这只会引入错误。
在Java中类型转换/从字符串转换为字符串并不难
// From integer to string
int i = 10;
String s = i + "";
// From string to integer
String s = "10";
int i = Integer.parseInt(s);
如果您有一个自定义类,则只需重写其toString()
方法并在传递给searchO()
方法之前对其进行调用
public class MyClass {
//...
@Override
public String toString() {
return //...
}
}
// Somewhere else in your code
MyClass c = // fetch a MyClass instance..
searchO(c.toString());
那为什么不定义为:
public boolean searchO(Object o) {
并修改此行以使用o.toString()
代替o
:
ResultSet rs = st.executeQuery("select * from `student` where `fname` = '" + o.toString() + "' ;");
您只需要确保传递的任何内容都会为toString()
方法返回所需的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.