实现通用接口

时间:2017-06-01 08:49:15

标签: java generics

我有一个接口Exec

public interface Exec<T, U> {
    U execute(final T context);
}

现在我可以有一个实现接口Exec的类,如下所示

public class BatchExec<T, U> implements Exec<List<T>, List<U>>

我怀疑是Exec接受T和U作为类型参数,在这种情况下我们将它作为List和List传递但是BatchExec需要T和U?

1 个答案:

答案 0 :(得分:1)

正如Oliver Charlesworth所指出的,U中的TBatchExex<...>Exec<T, U>中的BatchExecpublic class BatchExec<T, U> implements Exec<List<T>, List<U>> 不同。即如果你这样声明List<T>

List<U>

然后,执行方法签名将包含public List<U> execute(List<T> context) OtherbatchExec

public class OtherBatchExec<P, Q> implements Exec<List<P>, List<Q>> {
    @Override
    public List<Q> execute(List<P> context) {
        return null;
    }

}

这可能会令人困惑,所以让我们创建一个带有其他类型参数的Exec<List<String>, List<Integer>> exec = new BatchExec<String, Integer>(); Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<String, Integer>();

Exec<List<String>, List<Integer>> exec = new BatchExec<>();
Exec<List<String>, List<Integer>> otherExec = new OtherBatchExec<>();

只是为了演示它,你可以用同样的方式调用它们的构造函数:

<?php
function make_thumb($src, $dest, $desired_width) {

    /* read the source image */
    $source_image = imagecreatefromjpeg($src);
    $width = imagesx($source_image);
    $height = imagesy($source_image);

    /* find the "desired height" of this thumbnail, relative to the desired width  */
    $desired_height = floor($height * ($desired_width / $width));

    /* create a new, "virtual" image */
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height);

    /* copy source image at a resized size */
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);

    /* create the physical thumbnail image to its destination */
    imagejpeg($virtual_image, $dest);
}

$src="1494684586337H.jpg";
$dest="new.jpg";
$desired_width="200";
make_thumb($src, $dest, $desired_width);
?>

为了便于阅读,我也将类型参数添加到构造函数调用中。您也可以使用diamond operator

var $htmlOrBody = $('html, body'), // scrollTop works on <body> for some browsers, <html> for others
scrollTopPadding = 8;

$('input').focus(function() {
// get input tag's offset top position
var textareaTop = $(this).offset().top;
// scroll to the textarea
$htmlOrBody.scrollTop(textareaTop - scrollTopPadding);

// OR  To add animation for smooth scrolling, use this. 
//$htmlOrBody.animate({ scrollTop: textareaTop - scrollTopPadding }, 200);

});