简体   繁体   中英

How do I allow a function parameter to take on various objects types?

I want to be able to pass any object to the searchO method, such as td1.searchO("akash") or td1.searchO(1) . It should accept all objects as object class is a superclass of all.

How would I do this?

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;
    }
}

You might be interested in using overloading.

You will have two methods.

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
}

SECURITY NOTE: your SQL query is vulnerable to SQL injection. To avoid this threat, use PreparedStatement . Remember, never concatenate a variable's value to any query string.

Since you will be using you argument as a string filter (assuming fname is a db column with varchar / text type), leaving the type as String is more preferrable

You might think changing the parameter type into public boolean searchO(Object o ) and calling o.toString() will do the trick but it will just introduce bug if later down the track you pass a type with no proper toString() implementation

Type casting / conversion from / to String is not hard in Java

// From integer to string
int i = 10;
String s = i + "";

// From string to integer
String s = "10";
int i = Integer.parseInt(s);

If you have a custom class, just override its toString() method and call it before passing to searchO() method

public class MyClass {
  //...
  @Override
  public String toString() {
    return //...
  }
}

// Somewhere else in your code
MyClass c = // fetch a MyClass instance..
searchO(c.toString());

Then why don't you define it as:

public boolean searchO(Object o) {

and modify this line to use o.toString() instead of o :

ResultSet rs = st.executeQuery("select * from `student` where `fname` = '" + o.toString() + "' ;");

You just have to make sure that whatever you pass in returns a desired value for toString() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM