[英]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.