type information - The Need for RTTI

博客介绍了RTTI(Runtime type information),即运行时类型信息,它能在程序运行时发现和使用类型信息,有编译时已知所有类型和仅在运行时发现并使用类信息的反射机制两种形式,还提及了返回指定值元素顺序流的相关内容,并给出示例和参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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...-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值