下面列出了怎么用java.util.function.IntSupplier的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testNestedFunction() throws Exception {
MethodDescriptor getAsInt = MethodDescriptor.ofMethod(IntSupplier.class, "getAsInt", int.class);
MethodDescriptor addExact = MethodDescriptor.ofMethod(Math.class, "addExact", int.class, int.class, int.class);
final TestClassLoader cl = new TestClassLoader(getClass().getClassLoader());
try (ClassCreator creator = ClassCreator.builder().classOutput(cl).className("com.MyTest").interfaces(IntSupplier.class).build()) {
MethodCreator bc = creator.getMethodCreator("getAsInt", int.class);
ResultHandle seven = bc.invokeStaticMethod(addExact, bc.load(2), bc.load(5));
FunctionCreator f1 = bc.createFunction(IntSupplier.class);
BytecodeCreator f1bc = f1.getBytecode();
ResultHandle four = f1bc.invokeStaticMethod(addExact, seven, f1bc.load(- 3));
FunctionCreator f2 = f1bc.createFunction(IntSupplier.class);
BytecodeCreator f2bc = f2.getBytecode();
f2bc.returnValue(f2bc.invokeStaticMethod(addExact, seven, four));
f1bc.returnValue(f1bc.invokeInterfaceMethod(getAsInt, f2.getInstance()));
bc.returnValue(bc.invokeInterfaceMethod(getAsInt, f1.getInstance()));
}
Class<? extends IntSupplier> clazz = cl.loadClass("com.MyTest").asSubclass(IntSupplier.class);
IntSupplier supplier = clazz.getDeclaredConstructor().newInstance();
Assert.assertEquals(11, supplier.getAsInt());
}
public int getOrUpdate(int key, IntSupplier producer) {
int value = get(key);
if (value != notFound) {
return value;
}
synchronized (this) {
value = get(key);
if (value != notFound) {
return value;
}
value = producer.getAsInt();
put(key, value);
return value;
}
}
/** {@inheritDoc} */
@Override
public IHwLight createLight (final int surfaceID, final OutputID outputID, final IntSupplier supplier, final IntConsumer sendValueConsumer, final IntFunction<ColorEx> stateToColorFunction, final IHwButton button)
{
this.lightCounter++;
final String id = createID (surfaceID, outputID == null ? "LIGHT" + this.lightCounter : outputID.name ());
final MultiStateHardwareLight hardwareLight = this.hardwareSurface.createMultiStateHardwareLight (id);
final Supplier<? extends InternalHardwareLightState> valueSupplier = () -> new EncodedColorLightState (supplier.getAsInt (), stateToColorFunction);
final Consumer<? extends InternalHardwareLightState> hardwareUpdater = state -> {
final HardwareLightVisualState visualState = state == null ? null : state.getVisualState ();
final int encodedColorState = visualState == null ? 0 : supplier.getAsInt ();
sendValueConsumer.accept (encodedColorState);
};
final HwLightImpl lightImpl = new HwLightImpl (this.host, hardwareLight, valueSupplier, hardwareUpdater);
if (button != null)
button.addLight (lightImpl);
return lightImpl;
}
public final static int compare(long xAddr, long yAddr) {
IntSupplier scanx = scan(xAddr);
IntSupplier scany = scan(yAddr);
for (;;) {
int chx = scanx.getAsInt();
int chy = scany.getAsInt();
if ((chx == -1) && (chy == -1)) {
break;
}
int result = chx - chy;
if (result != 0) {
return result;
}
}
return 0;
}
public static int compare(long pX, long pY) {
IntSupplier scannerX = new FishUtf8(pX).scan();
IntSupplier scannerY = new FishUtf8(pY).scan();
for (;;) {
int x = scannerX.getAsInt();
int y = scannerY.getAsInt();
int result = x - y;
if (result != 0) {
return result;
}
if ((x == -1) && (y == -1)) {
break;
}
}
return 0;
}
private IntSupplier pendingTaskCounter(final EventLoopGroup eventLoopGroup) {
return () ->
StreamSupport.stream(eventLoopGroup.spliterator(), false)
.filter(eventExecutor -> eventExecutor instanceof SingleThreadEventExecutor)
.mapToInt(eventExecutor -> ((SingleThreadEventExecutor) eventExecutor).pendingTasks())
.sum();
}
@Override
public IntSupplier mapDecode(IntSupplier input) {
IntSupplier result = new IntSupplier() {
@Override
public int getAsInt() {
int ch = get(input);
return ch;
}
};
return result;
}
public DefaultCommandStoreDelay(CommandStore commandStore, IntSupplier delayLogLimitMicro){
this.commandStore = commandStore;
this.delayLogLimitMicro = delayLogLimitMicro;
for(int i=0;i<offsetDelays.length;i++){
offsetDelays[i] = new OffsetDelay();
}
}
private void waitForResult(int expect, IntSupplier supplier) {
for (; ; ) {
int actual = supplier.getAsInt();
if (expect == actual) {
return;
}
LOGGER.info("waiting for thread result, expect:{}, actual: {}.", expect, actual);
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
@Test public void testSupplierPerson() {
IntSupplier supplier = () -> {
Person manager1 = new Person(Title.MR, "James", "Wilks", 55);
return manager1.getAge();
};
assertEquals(55, supplier.getAsInt());
}
public String decode(IntSupplier supplier) {
StringBuilder buf = new StringBuilder();
IntSupplier output = mapDecode(supplier);
for (int ch = output.getAsInt(); ch != -1; ch=output.getAsInt()) {
buf.append((char)ch);
}
return buf.toString();
}
static String getString(TerminalNode rule, Decoder decoder) {
Token token = rule.getSymbol();
CharStream cs = token.getInputStream();
int pos = cs.index();
cs.seek(token.getStartIndex() + 1);
int len = token.getStopIndex() - token.getStartIndex() - 1;
IntSupplier supplier = new IntSupplier() {
int i = 0;
@Override
public int getAsInt() {
if (i >= len) {
return -1;
}
int ch = cs.LA(i + 1);
if (ch == '\\') {
i++;
ch = cs.LA(i + 1);
if (ch == '0') {
ch = 0;
}
else if (ch == 'n') {
ch = '\n';
}
else if (ch == 'r') {
ch = '\r';
}
else if (ch == 'Z') {
ch = '\032';
}
}
i++;
return ch;
}
};
String result = decoder.toString(supplier);
cs.seek(pos);
return result;
}
@Override
public int tx(IntSupplier paramSupplier) {
int j = 3;
if (m[j] == null) {
cache(j, "tx", IntSupplier.class);
}
return (Integer) Prepared.excute(m[j], new Object[]{paramSupplier}, this);
}
public DefaultProxyMonitorCollector(ScheduledExecutorService scheduled,
SimpleKeyedObjectPool<Endpoint, NettyClient> keyedObjectPool,
ProxyModel model, IntSupplier checkInterval) {
this.scheduled = scheduled;
this.model = model;
this.objectPool = keyedObjectPool.getKeyPool(new DefaultProxyEndpoint(model.getUri()));
this.checkInterval = checkInterval;
}
public static final IntSupplier scan(long addr) {
int format = Value.getFormat(null, addr);
if (format == Value.FORMAT_UNICODE16) {
return new Unicode16(addr).scan();
}
else if (format == Value.FORMAT_UTF8) {
return new FishUtf8(addr).scan();
}
else {
throw new IllegalArgumentException();
}
}
/** {@inheritDoc} */
@Override
public void addOutput (final IntSupplier supplier, final IntConsumer consumer)
{
this.supplier = supplier;
this.consumer = consumer;
}
public static String getString(long pValue) {
StringBuilder buf = new StringBuilder();
IntSupplier scan = new FishUtf8(pValue).scan();
int ch;
while ((ch=scan.getAsInt()) >= 0) {
buf.append((char)ch);
}
return buf.toString();
}
/** {@inheritDoc} */
@Override
public IHwLight createLight (final OutputID outputID, final IntSupplier supplier, final IntConsumer sendConsumer, final IntFunction<ColorEx> stateToColorFunction, final IHwButton button)
{
final IHwLight light = this.surfaceFactory.createLight (this.surfaceID, outputID, supplier, sendConsumer, stateToColorFunction, button);
if (outputID != null)
this.lights.put (outputID, light);
return light;
}
public DefaultProxyEndpointManager(IntSupplier checkInterval) {
this.healthCheckInterval = checkInterval;
this.scheduled = MoreExecutors.getExitingScheduledExecutorService(
new ScheduledThreadPoolExecutor(1, XpipeThreadFactory.create("ProxyEndpointManager")),
THREAD_POOL_TIME_OUT, TimeUnit.SECONDS);
this.healthChecker = new DefaultProxyEndpointHealthChecker(scheduled);
start();
}
OfInt(long size, IntSupplier s) {
super(size);
this.s = s;
}
public TaskCountEstimator(IntSupplier numberOfNodes)
{
this.numberOfNodes = requireNonNull(numberOfNodes, "numberOfNodes is null");
}
OfInt(long size, IntSupplier s) {
super(size);
this.s = s;
}
public IntSupplier scan() {
return new Scanner(this.addr + HEADER_SIZE, this.length);
}
public FloatArrayReservation(FloatConsumer applier, IntConsumer sizeApplier, FloatSupplier extractor, IntSupplier sizeExtractor) {
super(applier, sizeApplier, extractor, sizeExtractor);
}
IntSupplier getAccess(String owner, String name, String desc) {
return () -> acc(owner, name, desc, ACC_NOT_FOUND);
}
@Test(dataProvider = "checkFromIndexSizeProvider")
public void testCheckFromIndexSize(int fromIndex, int size, int length, boolean withinBounds) {
List<Integer> list = Collections.unmodifiableList(Arrays.asList(new Integer[] { fromIndex, size, length }));
String expectedMessage = withinBounds
? null
: Preconditions.outOfBoundsExceptionFormatter(IndexOutOfBoundsException::new).
apply("checkFromIndexSize", list).getMessage();
BiConsumer<Class<? extends RuntimeException>, IntSupplier> check = (ec, s) -> {
try {
int rIndex = s.getAsInt();
if (!withinBounds)
fail(String.format(
"Range [%d, %d + %d) is out of bounds of [0, %d), but was reported to be withing bounds", fromIndex, fromIndex, size, length));
assertEquals(rIndex, fromIndex);
}
catch (RuntimeException e) {
assertTrue(ec.isInstance(e));
if (withinBounds)
fail(String.format(
"Range [%d, %d + %d) is within bounds of [0, %d), but was reported to be out of bounds", fromIndex, fromIndex, size, length));
else
assertEquals(e.getMessage(), expectedMessage);
}
};
check.accept(AssertingOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
assertingOutOfBounds(expectedMessage, "checkFromIndexSize", fromIndex, size, length)));
check.accept(IndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
assertingOutOfBoundsReturnNull("checkFromIndexSize", fromIndex, size, length)));
check.accept(IndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length, null));
check.accept(ArrayIndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
Preconditions.outOfBoundsExceptionFormatter(ArrayIndexOutOfBoundsException::new)));
check.accept(StringIndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
Preconditions.outOfBoundsExceptionFormatter(StringIndexOutOfBoundsException::new)));
}
OfInt(long size, IntSupplier s) {
super(size);
this.s = s;
}
@Test(dataProvider = "checkIndexProvider")
public void testCheckIndex(int index, int length, boolean withinBounds) {
List<Integer> list = Collections.unmodifiableList(Arrays.asList(new Integer[] { index, length }));
String expectedMessage = withinBounds
? null
: Preconditions.outOfBoundsExceptionFormatter(IndexOutOfBoundsException::new).
apply("checkIndex", list).getMessage();
BiConsumer<Class<? extends RuntimeException>, IntSupplier> checker = (ec, s) -> {
try {
int rIndex = s.getAsInt();
if (!withinBounds)
fail(String.format(
"Index %d is out of bounds of [0, %d), but was reported to be within bounds", index, length));
assertEquals(rIndex, index);
}
catch (RuntimeException e) {
assertTrue(ec.isInstance(e));
if (withinBounds)
fail(String.format(
"Index %d is within bounds of [0, %d), but was reported to be out of bounds", index, length));
else
assertEquals(e.getMessage(), expectedMessage);
}
};
checker.accept(AssertingOutOfBoundsException.class,
() -> Preconditions.checkIndex(index, length,
assertingOutOfBounds(expectedMessage, "checkIndex", index, length)));
checker.accept(IndexOutOfBoundsException.class,
() -> Preconditions.checkIndex(index, length,
assertingOutOfBoundsReturnNull("checkIndex", index, length)));
checker.accept(IndexOutOfBoundsException.class,
() -> Preconditions.checkIndex(index, length, null));
checker.accept(ArrayIndexOutOfBoundsException.class,
() -> Preconditions.checkIndex(index, length,
Preconditions.outOfBoundsExceptionFormatter(ArrayIndexOutOfBoundsException::new)));
checker.accept(StringIndexOutOfBoundsException.class,
() -> Preconditions.checkIndex(index, length,
Preconditions.outOfBoundsExceptionFormatter(StringIndexOutOfBoundsException::new)));
}
public IntDataWriter(DataOutput output, IntSupplier extractor) {
super(output, extractor);
}
@Test(dataProvider = "checkFromIndexSizeProvider")
public void testCheckFromIndexSize(int fromIndex, int size, int length, boolean withinBounds) {
List<Integer> list = Collections.unmodifiableList(Arrays.asList(new Integer[] { fromIndex, size, length }));
String expectedMessage = withinBounds
? null
: Preconditions.outOfBoundsExceptionFormatter(IndexOutOfBoundsException::new).
apply("checkFromIndexSize", list).getMessage();
BiConsumer<Class<? extends RuntimeException>, IntSupplier> check = (ec, s) -> {
try {
int rIndex = s.getAsInt();
if (!withinBounds)
fail(String.format(
"Range [%d, %d + %d) is out of bounds of [0, %d), but was reported to be withing bounds", fromIndex, fromIndex, size, length));
assertEquals(rIndex, fromIndex);
}
catch (RuntimeException e) {
assertTrue(ec.isInstance(e));
if (withinBounds)
fail(String.format(
"Range [%d, %d + %d) is within bounds of [0, %d), but was reported to be out of bounds", fromIndex, fromIndex, size, length));
else
assertEquals(e.getMessage(), expectedMessage);
}
};
check.accept(AssertingOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
assertingOutOfBounds(expectedMessage, "checkFromIndexSize", fromIndex, size, length)));
check.accept(IndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
assertingOutOfBoundsReturnNull("checkFromIndexSize", fromIndex, size, length)));
check.accept(IndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length, null));
check.accept(ArrayIndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
Preconditions.outOfBoundsExceptionFormatter(ArrayIndexOutOfBoundsException::new)));
check.accept(StringIndexOutOfBoundsException.class,
() -> Preconditions.checkFromIndexSize(fromIndex, size, length,
Preconditions.outOfBoundsExceptionFormatter(StringIndexOutOfBoundsException::new)));
}