type information - The Need for RTTI

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/wangbingfengf98/article/details/93535195

RTTI: Runtime type information, discovers and uses type information while  a program is running.

It has two forms:

  • assumes we have all the types available at compile time
  • the reflection mechanism, which discovers and use class information solely at run time.
@SafeVarargs
static <T> Stream<T> of(T... values)

Returns a sequential ordered stream whose elements are the specified values.

Type Parameters:

T - the type of stream elements

Parameters:

values - the elements of the new stream

Returns:

the new stream

For example:

// typeinfo/Shapes.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.stream.*;

abstract class Shape {
  void draw() {
    System.out.println(this + ".draw()");
  }

  @Override
  public abstract String toString();// is abstract, force inheritors to override it.
}

class Circle extends Shape {
  @Override
  public String toString() {
    return "Circle";
  }
}

class Square extends Shape {
  @Override
  public String toString() {
    return "Square";
  }
}

class Triangle extends Shape {
  @Override
  public String toString() {
    return "Triangle";
  }
}

public class Shapes {
  public static void main(String[] args) {
    Stream.of(new Circle(), new Square(), new Triangle()).forEach(Shape::draw);
    // public interface Stream<T> extends BaseStream<T,Stream<T>>, since 1.8
  }
}
/* Output:
Circle.draw()
Square.draw()
Triangle.draw()
*/

references:

1. On Java 8 - Bruce Eckel

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

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

Guess you like

Origin blog.csdn.net/wangbingfengf98/article/details/93535195