如何将方法的String参数更改为未知的类类型

时间:2018-09-19 08:35:01

标签: java

我有一个接口,可以在方法回调中返回String值。如何更改方法中的返回String值,以允许使用Integer,Double,Custom Objets。等等

public interface ReturnHandler {
    void onResult(String value);
}

1 个答案:

答案 0 :(得分:3)

使用泛型,如下所示:

class Contractor  extends Model
{
    protected $table = 'Contractors';

    public $id;
    public $company;
    public $contact;
    public $landline;
    public $mobile;
    public $email;
    public $website;
    public $area;
    public $rate;
    public $address;
    public $gas_safe_reg_no;
    public $banned;
    public $ace_trades;
    public $created_at;
    public $updated_at;


    /*
        MODEL RELATIONSHIPS!!
    */
    // define one-to-one relationship between Contractors AND User
    public function user()  {
            return $this->belongsTo('App\User');
    }
    // Contractor connects on one-to-many with Contractor_Trade_Types.
    public function Contractor_Trade_Types()  {
            return $this->hasMany( 'App\Contractor_Trade_Types' );
    }   
    // Contractor connects on one-to-many with Contractor_Areas.
    public function Contractor_Areas()  {
            return $this->hasMany( 'App\Contractor_Areas' );
    }




    /**
    *       Get the trade types for a contractor.
    *       some contractors have more than one trade
    *       e.g. building and carpentry.
    */
    public function comments()  {
            return $this->hasMany('App\Contractor_Trade_Types');
    }


}




namespace App;

use Illuminate\Database\Eloquent\Model;



class Contractor_Trade_Types  extends Model
{
    protected $table = 'Contractor_Trade_Types';

    public $contractor_id;
    public $trade_id;


    // define relationship between Contractor_Trade_Types AND Contractor
    public function Contractor()    {
            return $this->belongsTo(' App\Contractor');
    }   



}


namespace App;

use Illuminate\Database\Eloquent\Model;



class Contractor_Areas  extends Model
{
    protected $table = 'Contractor_Areas';

    public $contractor_id;
    public $postcode;


    // define relationship between Contractor_Areas  AND Contractor
    public function Contractor()    {
            return $this->belongsTo(' App\Contractor');
    }   



}

..并像这样实现它:

interface ReturnHandler<T> {
    void onResult(T value);
}

或匿名:

class X implements ReturnHandler<Integer> {

    @Override
    public void onResult(Integer value) {
        ...
    }
}

另外一种选择是仅在方法上使用泛型:

ReturnHandler<String> handler = new ReturnHandler<String>() {

    @Override
    public void onResult(String value) {
       ...      
    }   
}

是这样实现的:

interface ReturnHandler {
    <T> void onResult(T value);
}

然后您可以拨打任何类型的class Y implements ReturnHandler { @Override public <T> void onResult(T value) { ... } }

onResult