欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

type information - Generic Class Syntax

程序员文章站 2022-05-12 22:03:49
...

The benefit of Class<?> is it indicates we aren’t just using a non-specific class reference by accident, or out of ignorance.

The reason for adding the generic syntax to Class references is only to provide compile-time type checking, so if we do something wrong we find out about it a little sooner. We can’t actually go astray with ordinary Class references, but if we make a mistake we won’t find out until run time, which can be inconvenient.

Here is a generic class syntax example. It stores a class reference, and later generates objects using newInstance() :

// typeinfo/DynamicSupplier.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.function.*;
import java.util.stream.*;

class CountedInteger {
  private static long counter;
  private final long id = counter++;

  @Override
  public String toString() {
    return Long.toString(id);
  }
}

public class DynamicSupplier<T> implements Supplier<T> {
  private Class<T> type;

  public DynamicSupplier(Class<T> type) {
    this.type = type;
  }

  public T get() {
    try {
      return type.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) {
    Stream.generate(new DynamicSupplier<>(CountedInteger.class))
        .skip(10)
        .limit(5)
        .forEach(System.out::println);
  }
}
/* Output:
10
11
12
13
14
*/

when class CountedInteger add a constructor has an argument, the error is:

Exception in thread "main" java.lang.RuntimeException: java.lang.InstantiationException: CountedInteger
        at DynamicSupplier.get(DynamicSupplier.java:34)
        at java.util.stream.StreamSpliterators$InfiniteSupplyingSpliterator$OfRef.tryAdvance(StreamSpliterators.java:1356)
        at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
        at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)

        at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
        at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
        at DynamicSupplier.main(DynamicSupplier.java:42)
Caused by: java.lang.InstantiationException: CountedInteger
        at java.lang.Class.newInstance(Class.java:427)
        at DynamicSupplier.get(DynamicSupplier.java:32)
        ... 10 more
Caused by: java.lang.NoSuchMethodException: CountedInteger.<init>()
        at java.lang.Class.getConstructor0(Class.java:3082)
        at java.lang.Class.newInstance(Class.java:412)
        ... 11 more

 


generate

static <T> Stream<T> generate(Supplier<T> s)

Returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.

Type Parameters:

T - the type of stream elements

Parameters:

s - the Supplier of generated elements

Returns:

a new infinite sequential unordered Stream


skip

Stream<T> skip(long n)

Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.

This is a stateful intermediate operation.

API Note:

While skip() is generally a cheap operation on sequential stream pipelines, it can be quite expensive on ordered parallel pipelines, especially for large values of n, since skip(n) is constrained to skip not just any n elements, but the first n elements in the encounter order. Using an unordered stream source (such as generate(Supplier)) or removing the ordering constraint with BaseStream.unordered() may result in significant speedups of skip() in parallel pipelines, if the semantics of your situation permit. If consistency with encounter order is required, and you are experiencing poor performance or memory utilization with skip() in parallel pipelines, switching to sequential execution with BaseStream.sequential() may improve performance.

Parameters:

n - the number of leading elements to skip

Returns:

the new stream

Throws:

IllegalArgumentException - if n is negative


limit

Stream<T> limit(long maxSize)

Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

This is a short-circuiting stateful intermediate operation.

API Note:

While limit() is generally a cheap operation on sequential stream pipelines, it can be quite expensive on ordered parallel pipelines, especially for large values of maxSize, since limit(n)is constrained to return not just any n elements, but the first n elements in the encounter order. Using an unordered stream source (such as generate(Supplier)) or removing the ordering constraint with BaseStream.unordered() may result in significant speedups of limit() in parallel pipelines, if the semantics of your situation permit. If consistency with encounter order is required, and you are experiencing poor performance or memory utilization with limit() in parallel pipelines, switching to sequential execution with BaseStream.sequential() may improve performance.

Parameters:

maxSize - the number of elements the stream should be limited to

Returns:

the new stream

Throws:

IllegalArgumentException - if maxSize is negative


@FunctionalInterface
public interface Supplier<T>

Represents a supplier of results.

There is no requirement that a new or distinct result be returned each time the supplier is invoked.

This is a functional interface whose functional method is get().

Since:

1.8

 

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/DynamicSupplier.java

3. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-

4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#limit-long-

5. https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html

相关标签: program language