小编Rog*_*gue的帖子

为什么Java 8不允许使用非公共默认方法?

我们来举个例子:

public interface Testerface {

    default public String example() {
        return "Hello";
    }

}

public class Tester implements Testerface {

    @Override
    public String example() {
        return Testerface.super.example() + " world!";
    }


}

public class Internet {

    public static void main(String[] args) {
        System.out.println(new Tester().example());
    }

}
Run Code Online (Sandbox Code Playgroud)

简单地说,这将打印出来Hello world!.但是说我正在使用返回值做其他事情Testerface#example,例如初始化数据文件并返回一个不应离开实现类的敏感内部值.为什么Java不允许在默认接口方法上使用访问修饰符?为什么它们不能被保护/私有并且可能被子类提升(类似于扩展父类的类如何为重写方法使用更可见的修饰符)?

一个常见的解决方案是转移到抽象类,但在我的特定情况下,我有一个枚举接口,所以这里不适用.我想它或者被忽略了,或者因为接口背后的原始想法是它们是可用方法的"契约",但我想我想要输入关于这个的内容.

我读过" 为什么"最终"在Java 8接口方法中不允许? ",其中指出:

默认方法的基本思想是:它是具有默认实现的接口方法,派生类可以提供更具体的实现

对我来说听起来就像可见性根本不会破坏那个方面.

与链接的问题一样,因为它看起来很难被关闭,所以在这个问题上会得到权威的答案,而不是基于意见的答案.

java java-8 default-method

31
推荐指数
1
解决办法
5624
查看次数

在所有方法调用中允许类型见证的重点是什么?

假设我们有两种方法,如下所示:

public static <T> T genericReturn() { /*...*/ }
public static String stringReturn() { /*...*/ }
Run Code Online (Sandbox Code Playgroud)

在调用任何方法时,无论是否有任何要求,您都可以提供类型见证:

String s;
s = Internet.<String>genericReturn(); //Type witness used in return type, returns a String
s = Internet.<Integer>stringReturn(); //Type witness ignored, returns a String
Run Code Online (Sandbox Code Playgroud)

但是我根本没有在Java中看到任何实际用途,除非无法推断出这种类型(这通常表明存在更大的问题).此外,当它没有被适当使用时被简单地忽略这一事实似乎违反直觉.那么在Java中有什么意义呢?

java generics

25
推荐指数
1
解决办法
1435
查看次数

从bash脚本运行节点

很简单,我正在尝试使用cron自动运行nodejs脚本,但是脚本本身似乎无法运行该文件.我的脚本很简单:

#!/usr/bin/env node
node /var/node/assets/js/update.js
Run Code Online (Sandbox Code Playgroud)

但是,在运行它时,它返回路径的开头不正确:

/home/dev/update.sh:2
node /var/node/assets/js/update.js
      ^^^
SyntaxError: Unexpected token var
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3
Run Code Online (Sandbox Code Playgroud)

bash是否存在实际问题,或者节点是否有特定的方法来执行此操作?我使用/ bin/env这样我可以拥有适当形式的"节点",无论版本如何.

bash shell node.js

20
推荐指数
2
解决办法
4万
查看次数

从lambda表达式中的方法返回值

我试图弄清楚如何从lambda表达式返回一个方法值:

public int findMissingNumber(Collection<Integer> ints) {
    Single<Integer> start = new Single<>(1);
    ints.stream().mapToInt(Integer::valueOf).parallel().forEach(i -> {
        if (i != start.setValue(start.getValue() + 1)) {
            //return here
        }
    });
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

但是,似乎return在lambda表达式中使用关键字将显式返回lambda函数本身.有没有某种方法可以打破或强制整个方法返回?

java lambda java-8

19
推荐指数
2
解决办法
3万
查看次数

为什么Collection的.addAll比手动添加慢?

我运行了两个测试用例(多次),似乎迭代地向我的列表添加值比使用更快 addAll

String[] rawArgs = new String[]{"one", "two", "three", "four", "five"};

// More efficient - 894 ns
List<String> list = new ArrayList<>();
for (String s : rawArgs) {
    list.add(s);
}


// Less efficient - 1340 ns
List<String> list = new ArrayList<>();
list.addAll(Arrays.asList(rawArgs));
Run Code Online (Sandbox Code Playgroud)

我通过我的IDE以及其他人获得笔记,后一种方法是将数组转换为该数据结构的"正确"方式.但如果它实际上比第一个慢,那么有什么优势(一些模糊的类型安全?),我应该使用第二个?

编辑 - 代码基准测试:

预热JVM,首先重新创建主类对象:

public static void main(String[] args) {
    Internet test;
    for (int i = 0; i < 15; i++) {
        test = new Internet(); // JVM warmup
    }
    test = new Internet();
    test.printOutput();
}
Run Code Online (Sandbox Code Playgroud)

我只是在操作的两端采用纳米级系统: …

java arrays collections

17
推荐指数
3
解决办法
8293
查看次数

为什么具有显式返回的空lambda和构造函数会导致编译器错误(Java Bug?)

我有一个可重现的测试用例:

public class TestCase {

    private final java.util.function.Consumer<Object> emptyCallback = result -> {};

    public TestCase() {
        return;
    }

    public static void main(String... args) {
        new TestCase();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用Java 8,更新51(Oracle JDK).使用IntelliJ和javac都无法编译.

IntelliJ输出:

Error(6, 7): java: variable result might not have been initialized
Run Code Online (Sandbox Code Playgroud)

javac输出:

TestCase.java:6: error: Variable result might not have been initialized
        return;
        ^
1 error
Run Code Online (Sandbox Code Playgroud)

现在奇怪的是,删除return;Consumer将修复错误.这是一个java bug,还是我在这里缺少一些语言设计?

编辑:这不是一个重复的构造函数如何返回一个值,这实际上是一个构造函数,并不是关于构造函数的返回值,而是变量初始化.

java lambda java-8

13
推荐指数
1
解决办法
195
查看次数

在百里香中删除或放置方法

我想@RequestMapping(value = "", method = RequestMethod.DELETE)在春天从百里香的形式打电话.

是否有可能从百里香叶调用删除或放置请求映射方法?

请对此提出建议.

spring-mvc thymeleaf

10
推荐指数
3
解决办法
1万
查看次数

根据toMap集合中的值过滤流

我有一个情况,我Player在开发项目中有对象,任务只是测量距离并返回低于某个阈值的结果.当然,我想以最简洁的方式使用流.

目前,我有一个映射流的解决方案,然后通过迭代器过滤:

Stream<Player> str = /* source of my player stream I'm filtering */;
Map<Player, Double> dists = str.collect(Collectors.toMap(...)); //mapping function
Iterator<Map.Entry<Player, Double>> itr = map.entrySet().iterator();
while (itr.hasNext()) {
    if (itr.next().getValue() <= radiusSquared) {
        itr.remove();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我想要实现的是在对流进行操作时执行此过滤的内容,即"如果此谓词失败,不收集",则尝试并保存第二次迭代.另外,我不想计算两次距离,所以通过映射函数进行过滤,然后重新映射不是一个合理的解决方案.

我想到的唯一真正可行的解决方案是映射到a Pair<A, B>,但如果有某种形式的二进制流的原生支持,那就更好了.

java的流API中是否有本机支持?

java java-8 java-stream

8
推荐指数
1
解决办法
1418
查看次数

在Java 8中删除了javax的NotNull吗?

纵观文档NotNull的Java 7下,你可以看到javax.validation.constraints.NotNull是一个有效的和记录注释.但是,在导航到Java 8的同一页面时,我收到404.

Netbeans建议导入com.avaje.ebean.validation.NotNull,这不是我想要的(它不支持几乎同样多的展示位置).

我听说过这个标签NonNull,但我找不到java文档,也不能在netbeans中导入它.我打算在Java 8中使用什么?

java netbeans annotations java-8

6
推荐指数
1
解决办法
4181
查看次数

无法用maven遮住罐子(INVOKESPECIAL/STATIC)

完整的错误消息:

无法执行目标org.apache.maven.plugins:maven-shade-plugin:2.3:项目阴影(默认) - :创建阴影jar时出错:接口上的INVOKESPECIAL/STATIC需要ASM 5 - > [帮助1]

我试图阴影的jarfile位于我自己的远程存储库中,使用sonatype nexus.这是我的pom配置:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.codelanx</groupId>
    <artifactId>phanaticprison</artifactId>
    <version>1.0.0</version>
    <name>PhanaticPrison</name>
    <packaging>jar</packaging>

    <repositories>
        <repository>
            <id>bukkit-repo</id>
            <url>http://repo.bukkit.org/content/repositories/public/</url>
        </repository>
        <repository>
            <id>codelanx-repo</id>
            <url>http://repo.codelanx.com/content/repositories/public/</url>
        </repository>
    </repositories>
    <licenses>
        <license>
            <name>Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International</name>
            <url>https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <artifactSet>
                        <includes>
                            <include>com.codelanx:codelanxlib</include>
                        </includes>
                    </artifactSet>
                    <minimizeJar>true</minimizeJar>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <targetPath>.</targetPath>
                <directory>${basedir}/src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <finalName>${project.name}</finalName>
    </build> …
Run Code Online (Sandbox Code Playgroud)

java eclipse netbeans maven maven-shade-plugin

6
推荐指数
1
解决办法
6671
查看次数