undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,154 @@
/*
* Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8231461
* @summary static/instance overload leads to 'unexpected static method found in unbound lookup' when resolving method reference
* @library /lib/combo /tools/lib /tools/javac/lib
* @modules
* jdk.compiler/com.sun.tools.javac.api
* jdk.compiler/com.sun.tools.javac.util
* @run junit BoundUnboundSearchTest
*/
import java.util.function.*;
import javax.tools.Diagnostic;
import com.sun.tools.javac.api.ClientCodeWrapper.DiagnosticSourceUnwrapper;
import com.sun.tools.javac.util.Assert;
import com.sun.tools.javac.util.JCDiagnostic;
import org.junit.jupiter.api.Test;
import tools.javac.combo.CompilationTestCase;
class BoundUnboundSearchTest extends CompilationTestCase {
static final String TEMPLATE =
"""
import java.util.function.*;
class Test {
#CANDIDATES
void m() {
Function<String, String> f = Test::foo;
}
}
""";
BoundUnboundSearchTest() {
setDefaultFilename("Test.java");
setCompileOptions(new String[]{"--debug=dumpMethodReferenceSearchResults"});
}
private Consumer<Diagnostic<?>> getDiagConsumer(final int boundCandidate, final int unboundCandidate) {
return diagWrapper -> {
JCDiagnostic diagnostic = ((DiagnosticSourceUnwrapper)diagWrapper).d;
Object[] args = diagnostic.getArgs();
if (args[0].toString().equals("bound")) {
Assert.check(args[2].equals(boundCandidate));
} else if (args[0].toString().equals("unbound")) {
Assert.check(args[2].equals(unboundCandidate));
}
};
}
@Test
void test() {
assertOK(
getDiagConsumer(0, -1),
TEMPLATE.replaceFirst("#CANDIDATES",
"""
public String foo(Object o) { return "foo"; } // candidate 0
public static String foo(String o) { return "bar"; } // candidate 1
"""
)
);
assertOK(
getDiagConsumer(0, -1),
TEMPLATE.replaceFirst("#CANDIDATES",
"""
public static String foo(Object o) { return "foo"; } // candidate 0
public static String foo(String o) { return "bar"; } // candidate 0
"""
)
);
assertFail("compiler.err.prob.found.req",
getDiagConsumer(0, -1),
TEMPLATE.replaceFirst("#CANDIDATES",
"""
public static String foo(Object o) { return "foo"; } // candidate 0
public String foo(String o) { return "bar"; } // candidate 1
"""
)
);
assertFail("compiler.err.prob.found.req",
getDiagConsumer(0, -1),
TEMPLATE.replaceFirst("#CANDIDATES",
"""
public String foo(Object o) { return "foo"; } // candidate 0
public String foo(String o) { return "bar"; } // candidate 1
"""
)
);
assertFail("compiler.err.invalid.mref",
getDiagConsumer(-1, -1),
"""
import java.util.function.*;
public class Test {
public String foo(Object o) { return "foo"; }
public static String foo(String o) { return "bar"; }
public void test() {
// method bar doesn't exist
Function<String, String> f = Test::bar;
}
}
"""
);
assertOK(
getDiagConsumer(0, -1),
"""
import java.util.function.*;
interface Intf {
Object apply(String... args);
}
public class Test {
public static Object foo(Object o) { return "bar"; }
public final Object foo(Object... o) { return "foo"; }
public void test() {
Intf f = this::foo;
}
}
"""
);
}
}

View file

@ -0,0 +1,118 @@
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test bridge methods in certain SAM conversion
* @compile BridgeMethod.java
* @run main BridgeMethod
*/
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public class BridgeMethod {
interface H {Object m();}
interface K<T> {void m(T t);}
interface L extends K<String> {} //generic substitution
interface M {void m(String s);}
interface KM extends K<String>, M{} //generic substitution
interface N extends H {String m();} //covariant return
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
static void bar(String s) {
System.out.println("BridgeMethod.bar(String) " + s);
}
String moo() {
return "moo";
}
private static Set<String> setOfStringObject() {
Set<String> s = new HashSet<>();
s.add("java.lang.String");
s.add("java.lang.Object");
return s;
}
public static void main(String[] args) {
L la = BridgeMethod::bar; //static reference
la.m("hi");
Class<? extends L> c1 = la.getClass();
Method[] methods = c1.getDeclaredMethods();
Set<String> types = setOfStringObject();
System.out.println("methods in SAM conversion of L:");
for(Method m : methods) {
assertTrue(m.getName().equals("m"));
System.out.println(m.toGenericString());
Class[] parameterTypes = m.getParameterTypes();
assertTrue(parameterTypes.length == 1);
assertTrue(types.remove(parameterTypes[0].getName()));
}
assertTrue(types.isEmpty() || (types.size() == 1 && types.contains("java.lang.String")));
KM km = BridgeMethod::bar;
//km.m("hi"); //will be uncommented when CR7028808 fixed
Class<? extends KM> c2 = km.getClass();
methods = c2.getDeclaredMethods();
types = setOfStringObject();
System.out.println("methods in SAM conversion of KM:");
for(Method m : methods) {
assertTrue(m.getName().equals("m"));
System.out.println(m.toGenericString());
Class<?>[] parameterTypes = m.getParameterTypes();
assertTrue(parameterTypes.length == 1);
assertTrue(types.remove(parameterTypes[0].getName()));
}
assertTrue(types.isEmpty());
N n = new BridgeMethod()::moo; //instance reference
assertTrue( n.m().equals("moo") );
assertTrue( ((H)n).m().equals("moo") );
Class<? extends N> c3 = n.getClass();
methods = c3.getDeclaredMethods();
types = setOfStringObject();
System.out.println("methods in SAM conversion of N:");
for(Method m : methods) {
System.out.println(m.toGenericString());
if (m.getName().equals("m")) {
Class<?> returnType = m.getReturnType();
assertTrue(types.remove(returnType.getName()));
}
}
assertTrue(types.size() == 1); //there's a bridge
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8182401
* @summary Verification error for enclosing instance capture inside super constructor invocation
* @run main ImplicitEnclosingInstanceTest
*/
import java.util.function.Function;
public class ImplicitEnclosingInstanceTest {
static String cookie = "deadbeef";
static Object f(Function<String, Object> f) {
return f.apply("feed");
}
class S {
S(Object s) {
cookie += "face";
}
}
class A {
A(String s) {
cookie = s;
}
}
class B extends S {
B() {
super(f(A::new));
}
}
public static void main(String[] args) {
new ImplicitEnclosingInstanceTest().new B();
if (!cookie.equals("feedface"))
throw new AssertionError("Incorrect cookie!");
}
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8292975
* @summary Javac produces code that crashes with LambdaConversionException
* @run main IntersectionParameterTypeTest
*/
import java.util.function.BiFunction;
public class IntersectionParameterTypeTest {
sealed interface Term {
record Lit() implements Term {}
record Lam(String x, Term a) implements Term {}
}
public static <U, T> void call(BiFunction<U, T, T> op, U x, T t) {
op.apply(x, t);
}
public static void main(String[] args) {
// this code works
call(Term.Lam::new, "x", (Term) new Term.Lit());
// this does not
call(Term.Lam::new, "x", new Term.Lit());
}
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8269983
* @summary BootstrapMethodError with method reference and intersection type
* @run main IntersectionParameterTypeTest2
*/
public class IntersectionParameterTypeTest2 {
public static void main(String[] args) {
f();
}
static <T extends Comparable<T> & G> C<T> f() {
return new C<>(Q::g);
}
public interface G {}
private interface E<T> {
void g(Q g, T value);
}
static class C<T extends Comparable<?>> {
C(E<T> g) {}
}
static class Q {
void g(G g) {}
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8141508
* @summary Test that Call site initialization exception is not thrown when the method
reference receiver is of intersection type.
* @run main IntersectionTypeReceiverTest
*/
import java.time.LocalDate;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
public class IntersectionTypeReceiverTest {
public static void main(String[] args) {
String output = valueOfKey(Size.class, LocalDate.now()).toString();
if (!"Optional[S]".equals(output))
throw new AssertionError("Unexpected output: " + output);
}
enum Size implements Supplier<LocalDate> {
S, M, L;
@Override
public LocalDate get() {
return LocalDate.now();
}
}
public static <K, T extends Enum<T> & Supplier<K>> Optional<T> valueOfKey(Class<T> enumType, K key) {
return valueOf(enumType, key, T::get);
}
public static <K, T extends Enum<T>> Optional<T> valueOf(Class<T> enumType, K key, Function<T, K> keyExtractor) {
return EnumSet.allOf(enumType).stream().filter(t -> Objects.equals(keyExtractor.apply(t), key)).findFirst();
}
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8142476
* @summary Test that Call site initialization exception is not thrown when the method
reference receiver is of intersection type.
* @run main IntersectionTypeReceiverTest2
*/
public class IntersectionTypeReceiverTest2 {
interface I {
}
interface J {
void foo();
}
static <T extends I & J> void bar(T t) {
Runnable r = t::foo;
}
public static void main(String[] args) {
class A implements I, J {
public void foo() {
}
}
bar(new A());
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test static method reference
* @compile MethodRef1.java
* @run main MethodRef1
*/
public class MethodRef1 {
static interface A {void m();}
static interface B {void m(int i);}
static interface C {String m(String s);}
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
static void foo(int x) {
System.out.println("MethodRef1.foo(int) " + x);
}
static void bar() {
System.out.println("MethodRef1.bar()");
}
static void bar(int x) {
System.out.println("MethodRef1.bar(int) " + x);
}
static String bar(String s) {
return "MethodRef1.bar(String) " + s;
}
public static void main(String[] args) {
A a = MethodRef1::bar; //static reference to bar()
a.m();
B b = MethodRef1::foo; //static reference to foo(int), (int) omitted because method foo is not overloaded
b.m(1);
b = MethodRef1::foo; //static reference to foo(int)
b.m(1);
b = MethodRef1::bar; //static reference to bar(int)
b.m(2);
C c = MethodRef1::bar; //static reference to bar(String)
assertTrue( c.m("hi").equals("MethodRef1.bar(String) hi") );
}
}

View file

@ -0,0 +1,69 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test instance method reference
* @compile MethodRef2.java
* @run main MethodRef2
*/
public class MethodRef2 {
static interface A {String m();}
static interface B {String m(int i);}
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
String moo() {
return "moo";
}
String wahoo() {
return "wahoo";
}
String wahoo(int x) {
return "wahoo " + x;
}
public static void main(String[] args) {
MethodRef2 mr = new MethodRef2();
A a = mr::moo; //instance reference to moo()
assertTrue( a.m().equals("moo") );
a = new MethodRef2()::wahoo; //instance reference to wahoo()
assertTrue( a.m().equals("wahoo") );
B b = mr::wahoo; //instance reference to wahoo(int)
assertTrue( b.m(4).equals("wahoo 4") );
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test unbound method reference
* @compile MethodRef3.java
* @run main MethodRef3
*/
public class MethodRef3 {
static interface A { String m(MethodRef3 mr); }
static interface B { String m(MethodRef3 mr, String s); }
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
String moo() {
return "moo";
}
String wahoo(String s) {
return "wahoo " + s;
}
public static void main(String[] args) {
MethodRef3 mr = new MethodRef3();
A a = MethodRef3::moo; //unbound reference to moo()
assertTrue( a.m(mr).equals("moo") );
B b = MethodRef3::wahoo; //unbound reference to wahoo()
assertTrue( b.m(mr, "hi").equals("wahoo hi") );
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test constructor reference
* @compile MethodRef4.java
* @run main MethodRef4
*/
public class MethodRef4 {
static interface A {Fee<String> m();}
static interface B {Fee<String> m(String s);}
static interface C {Object m();}
static class Fee<T> {
private T t;
public Fee() {
System.out.println("Fee<T> instantiated");
}
public Fee(T t) {
this.t = t;
System.out.println("Fee<T> instantiated: " + t);
}
public void make() {
System.out.println(this + ": make()");
}
}
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
public static void main(String[] args) {
A a = Fee<String>::new; //constructor reference to Fee<T>()
a.m().make();
B b = Fee<String>::new; //constructor reference to Fee<T>(String)
b.m("hi").make();
C c = MethodRef4::new; //constructor reference to MethodRef4()
assertTrue( c.m() instanceof MethodRef4 );
c = MethodRef4::new; //constructor reference to MethodRef4()
assertTrue( c.m() instanceof MethodRef4 );
c = Fee<String>::new; //constructor reference to Fee<T>()
assertTrue( c.m() instanceof Fee );
}
}

View file

@ -0,0 +1,96 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test method reference with SAM interface Comparator<T>
* @compile MethodRef5.java
* @run main MethodRef5
*/
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class MethodRef5 {
static class Person {
private String firstName;
private String lastName;
private int age;
public Person() { }
public Person(String fn, String ln, int a) {
firstName = fn;
lastName = ln;
age = a;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
//the following 2 methods are signature-compatible with Comparator<Person>.compare():
public static int compareByAge(Person a, Person b) {
return a.age - b.age;
}
public int compareByLastName(Person a, Person b) {
return a.lastName.compareToIgnoreCase(b.lastName);
}
}
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("John", "Smith", 49));
persons.add(new Person("Abraham", "Lincoln", 30));
persons.add(new Person("George", "Washington", 29));
persons.add(new Person("Peter", "Derby", 50));
Collections.sort(persons, Person::compareByAge);//static method reference to compareByAge(Person, Person)
String age = "";
for (Person p : persons) {
age += p.getAge() + " ";
}
assertTrue( (age.equals("29 30 49 50 ")) );
Collections.sort(persons, new Person()::compareByLastName);//instance method reference to compareByLastName(Person, Person)
String lastName = "";
for (Person p : persons) {
lastName += p.getLastName() + " ";
}
assertTrue( lastName.equals("Derby Lincoln Smith Washington ") );
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test that the most specific reference is selected when method parameters are elided
* @compile MethodRef6.java
* @run main MethodRef6
*/
public class MethodRef6 {
static interface A { String make(Integer i); }
static interface B { String make(Number i); }
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
static String m(Object o) {
return "Object " + o;
}
static String m(Number n) {
return "Number " + n;
}
static String m(Integer i) {
return "Integer " + i;
}
static String m(int i) {
return "int " + i;
}
public static void main(String[] args) {
A a = MethodRef6::m;
assertTrue(a.make(1).equals("Integer 1"));//method parameter type inferred from SAM descriptor, boxing applied
B b = MethodRef6::m;
assertTrue(b.make(1).equals("Number 1"));//method parameter type inferred from SAM descriptor, boxing and widen applied
}
}

View file

@ -0,0 +1,105 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test that parameter types are inferred from SAM descriptor when method parameters are elided,
with different types of method references
* @compile MethodRef7.java
* @run main MethodRef7
*/
public class MethodRef7 {
static interface A {void m();}
static interface A2 {void m(int n);}
static interface B {String m();}
static interface B2 {String m(int n);}
static interface C {String m(MethodRef7 mr);}
static interface C2 {String m(MethodRef7 mr, int n);}
static interface D {Fee<String> m();}
static interface D2 {Fee<String> m(String s);}
static class Fee<T> {
public Fee() {
System.out.println("Fee<T> instantiated");
}
public Fee(String s) {
System.out.println("Fee<T> instantiated: " + s);
}
}
private static void assertTrue(boolean cond) {
if (!cond)
throw new AssertionError();
}
static void bar() {
System.out.println("MethodRef_neg1.bar()");
}
static void bar(int x) {
System.out.println("MethodRef_neg1.bar(int) " + x);
}
String wahoo() {
return "wahoo";
}
String wahoo(int x) {
return "wahoo " + x;
}
public static void main(String[] args) {
A a = MethodRef7::bar; //static reference to bar()
a.m();
A2 a2 = MethodRef7::bar; //static reference to bar(int x)
a2.m(10);
MethodRef7 mr = new MethodRef7();
B b = mr::wahoo; //instance reference to wahoo()
assertTrue(b.m().equals("wahoo"));
B2 b2 = mr::wahoo; //instance reference to wahoo(int x)
assertTrue(b2.m(1).equals("wahoo 1"));
C c = MethodRef7::wahoo; //unbound reference to wahoo()
assertTrue(c.m(mr).equals("wahoo"));
C2 c2 = MethodRef7::wahoo; //unbound reference to wahoo(int x)
assertTrue(c2.m(mr, 2).equals("wahoo 2"));
D d = Fee<String>::new; //constructor reference to Fee()
D2 d2 = Fee<String>::new; //constructor reference to Fee(String s)
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8063052
* @summary Inference chokes on wildcard derived from method reference
* @compile MethodRef8.java
*/
public class MethodRef8 {
void test(Box<? extends Box<? extends Number>> b) {
Number n1 = b.map(Box::get).get();
Number n2 = b.<Number>map(Box::get).get();
}
interface Func<S,T> { T apply(S arg); }
interface Box<T> {
T get();
<R> Box<R> map(Func<T,R> f);
}
}

View file

@ -0,0 +1,20 @@
/**
* @test /nodynamiccopyright/
* @bug 8139245
* @summary compiler crashes with exception on int:new method reference and generic method inference
* @compile/fail/ref=MethodRefIntColonColonNewTest.out -XDrawDiagnostics MethodRefIntColonColonNewTest.java
*/
public class MethodRefIntColonColonNewTest {
interface SAM<T> {
T m(T s);
}
static <T> SAM<T> infmethod(SAM<T> t) { return t; }
public static void meth() {
SAM<Object> s = infmethod(int::new);
s.m();
}
}

View file

@ -0,0 +1,3 @@
MethodRefIntColonColonNewTest.java:17:35: compiler.err.type.found.req: int, (compiler.misc.type.req.class.array)
MethodRefIntColonColonNewTest.java:18:10: compiler.err.cant.apply.symbol: kindname.method, m, java.lang.Object, compiler.misc.no.args, kindname.interface, MethodRefIntColonColonNewTest.SAM<T>, (compiler.misc.arg.length.mismatch)
2 errors

View file

@ -0,0 +1,72 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8044748
* @summary JVM cannot access constructor though ::new reference although can call it directly
*/
public class MethodRefNewInnerBootstrap {
interface Constructor {
public MyTest execute(int i);
}
public class MyTest {
public MyTest(int i) { System.out.println("Constructor executed " + i); }
}
public Constructor getConstructor() {
return MyTest::new;
}
public static void main(String argv[]) {
new MethodRefNewInnerBootstrap().call();
}
public void call() {
MyTest mt = new MyTest(0);
Constructor c1 = MyTest::new;
c1.execute(1);
Constructor c2 = getConstructor();
c2.execute(2);
Constructor c3 = new Constructor() {
public MyTest execute(int i) {
return new MyTest(3);
}
};
c3.execute(3);
Constructor c4 = new Constructor() {
public MyTest execute(int i) {
Constructor c = MyTest::new;
return c.execute(i);
}
};
c4.execute(4);
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8037404
* @summary javac NPE or VerifyError for code with constructor reference of inner class
*/
import java.util.function.Supplier;
import java.util.stream.Stream;
public class MethodRefNewInnerInLambdaNPE1 {
public static void main(String[] args) {
if (new MethodRefNewInnerInLambdaNPE1().getList().get().getClass() != TT.class)
throw new AssertionError("sanity failed");
}
Supplier<TT> getList() {
return () -> Stream.of(1).map(TT::new).findFirst().get();
}
class TT {
public TT(int i) {
}
}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8044737
* @summary Lambda: NPE while obtaining method reference through lambda expression
* @compile MethodRefNewInnerInLambdaNPE2.java
*/
public class MethodRefNewInnerInLambdaNPE2 {
interface Constructor {
MyTest execute();
}
class MyTest {
MyTest() { System.out.println("Constructor executed"); }
}
public Constructor getConstructor() {
return getConstructor(() -> { return MyTest::new; });
}
public static void main(String argv[]) {
MethodRefNewInnerInLambdaNPE2 t = new MethodRefNewInnerInLambdaNPE2();
MyTest mytest = t.getConstructor().execute();
}
Constructor getConstructor(Wrapper arg) {
return arg.unwrap();
}
interface Wrapper {
Constructor unwrap();
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8037404
* @summary javac NPE or VerifyError for code with constructor reference of inner class
*/
import java.util.function.Function;
import java.util.stream.Stream;
public class MethodRefNewInnerInLambdaVerify1 {
public static void main(String[] args) {
if (new MethodRefNewInnerInLambdaVerify1().map().apply(1).getClass() != TT.class)
throw new AssertionError("sanity failed");
}
Function<Integer,TT> map() {
return (i) -> Stream.of(i).map(TT::new).findFirst().get();
}
class TT {
public TT(int i) {
}
}
}

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8038776
* @summary VerifyError when running successfully compiled java class
*/
import java.util.function.Function;
/**
* Derived from code by:
* @author Yawkat
*/
public class MethodRefNewInnerInLambdaVerify2 {
public static void main(String[] args) { new MethodRefNewInnerInLambdaVerify2().runTest(); }
private void runTest() {
Worker worker = new Worker();
run(() -> worker.check(field -> new SomeClass(field)));
run(() -> worker.check(SomeClass::new));
}
private void run(Runnable runnable) {
runnable.run();
}
private class SomeClass {
final Object field;
SomeClass(Object field) {
this.field = field;
}
}
private static class Worker {
void check(Function<Object, SomeClass> i) {
if (!i.apply("frank").field.equals("frank")) throw new AssertionError("sanity failed");
}
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8038776
* @summary VerifyError when running successfully compiled java class
*/
import java.util.function.Function;
/**
* Derived from code by:
* @author Yawkat
*/
public class MethodRefNewInnerInLambdaVerify2simple {
public static void main(String[] args) { new MethodRefNewInnerInLambdaVerify2simple().runTest(); }
private void runTest() {
Runnable r = (() -> { Sup w = SomeClass::new; } );
}
private class SomeClass {
SomeClass() { }
}
}
interface Sup {
Object get();
}

View file

@ -0,0 +1,24 @@
/*
* @test /nodynamiccopyright/
* @bug 8029633
* @summary Raw inner class constructor ref should not perform diamond inference
* @compile/fail/ref=MethodRefNewInnerRawTest.out -Werror -Xlint:unchecked -XDrawDiagnostics MethodRefNewInnerRawTest.java
*/
import java.util.function.*;
class MethodRefNewInnerRawTest<T> {
class Inner1 {}
class Inner2<U> {}
Supplier<MethodRefNewInnerRawTest.Inner1> s1 = MethodRefNewInnerRawTest.Inner1::new;
Supplier<MethodRefNewInnerRawTest.Inner2> s2 = MethodRefNewInnerRawTest.Inner2::new;
Supplier<MethodRefNewInnerRawTest<T>.Inner1> s3 = MethodRefNewInnerRawTest.Inner1::new;
Supplier<MethodRefNewInnerRawTest<T>.Inner2<String>> s4 = MethodRefNewInnerRawTest.Inner2::new;
static class Outer {
class Inner3<U> {}
Supplier<Outer.Inner3<String>> s5 = Outer.Inner3::new;
}
}

View file

@ -0,0 +1,5 @@
MethodRefNewInnerRawTest.java:16:55: compiler.warn.prob.found.req: (compiler.misc.unchecked.assign), MethodRefNewInnerRawTest.Inner1, MethodRefNewInnerRawTest<T>.Inner1
MethodRefNewInnerRawTest.java:17:63: compiler.warn.prob.found.req: (compiler.misc.unchecked.assign), MethodRefNewInnerRawTest.Inner2, MethodRefNewInnerRawTest<T>.Inner2<java.lang.String>
- compiler.err.warnings.and.werror
1 error
2 warnings

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8048121
* @summary javac complex method references: revamp and simplify
*/
public class MethodRefQualifier1 {
interface SAM {
void m();
}
static int count = 0;
static void assertTrue(boolean cond, String msg) {
if (!cond)
throw new AssertionError(msg);
}
MethodRefQualifier1 check() {
count++;
return this;
}
void ido(Object... args) { }
public static void main(String[] args) {
new MethodRefQualifier1().test();
}
void test() {
count = 0;
SAM s = check()::ido;
assertTrue(count == 1, "creation: unexpected: " + count);
count = 0;
s.m();
assertTrue(count == 0, "evaluation: unexpected: " + count);
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8048121
* @summary javac complex method references: revamp and simplify
*
* Make sure that the method reference receiver is evaluated exactly once
* even in this bridging case.
*/
public class MethodRefSingleRefEvalBridge {
interface SAM {
int m();
}
class ZZ {
// private to force bridging
private int four() { return 4; }
}
static int count = 0;
ZZ azz = new ZZ();
static void assertEqual(int expected, int got) {
if (got != expected)
throw new AssertionError("Expected " + expected + " got " + got);
}
public static void main(String[] args) {
new MethodRefSingleRefEvalBridge().test();
}
ZZ check() {
count++;
return azz;
}
void test() {
count = 0;
SAM s = check()::four;
assertEqual(1, count);
count = 0;
assertEqual(4, s.m());
assertEqual(0, count);
}
}

View file

@ -0,0 +1,22 @@
/*
* @test /nodynamiccopyright/
* @bug 8210483
* @summary AssertionError in DeferredAttr at setOverloadKind caused by JDK-8203679
* @compile/fail/ref=MethodRefStuck.out -XDrawDiagnostics MethodRefStuck.java
*/
import java.util.Optional;
import java.util.stream.Stream;
public abstract class MethodRefStuck {
public static void main(Stream<String> xs, Optional<String> x) {
xs.map(
c -> {
return new I(x.map(c::equals));
});
}
static class I {
I(boolean i) {}
}
}

View file

@ -0,0 +1,2 @@
MethodRefStuck.java:15:18: compiler.err.cant.apply.symbol: kindname.constructor, I, boolean, java.util.Optional<java.lang.Boolean>, kindname.class, MethodRefStuck.I, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.infer.no.conforming.instance.exists: U, java.util.Optional<U>, boolean))
1 error

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2018, Google LLC. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8213908
* @summary AssertionError in DeferredAttr at setOverloadKind
* @compile MethodRefStuck2.java
*/
import java.util.Optional;
import java.util.stream.Stream;
public abstract class MethodRefStuck2 {
abstract void f(long c);
interface I {
I g(String o);
}
private void test(Stream<I> is, Optional<String> o) {
f(
is.map(
i -> {
o.ifPresent(i::g);
return null;
})
.count());
}
}

View file

@ -0,0 +1,30 @@
/*
* @test /nodynamiccopyright/
* @bug 8249261
* @summary Verify method references as conditions to conditional expressions
* are handled properly.
* @compile/fail/ref=MethodRefStuck8249261.out -XDrawDiagnostics MethodRefStuck8249261.java
*/
class MethodRefStuck8249261 {
void p(int padding) {}
static boolean t() {
return true;
}
private void test() {
p(MethodRefStuck8249261::t);
p((MethodRefStuck8249261::t));
p(MethodRefStuck8249261::t + 1);
p(MethodRefStuck8249261::t ? 1 : 0);
p(true ? MethodRefStuck8249261::t : 0);
p(switch (MethodRefStuck8249261::t) { default -> 0; });
p(() -> true);
p((() -> true));
p((() -> true) + 1);
p((() -> true) ? 1 : 0);
p(true ? (() -> true) : 0);
p(switch ((() -> true)) { default -> 0; });
}
}

View file

@ -0,0 +1,13 @@
MethodRefStuck8249261.java:17:9: compiler.err.cant.apply.symbol: kindname.method, p, int, @11, kindname.class, MethodRefStuck8249261, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.not.a.functional.intf: int))
MethodRefStuck8249261.java:18:9: compiler.err.cant.apply.symbol: kindname.method, p, int, @11, kindname.class, MethodRefStuck8249261, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.not.a.functional.intf: int))
MethodRefStuck8249261.java:19:11: compiler.err.unexpected.mref
MethodRefStuck8249261.java:20:11: compiler.err.prob.found.req: (compiler.misc.not.a.functional.intf: boolean)
MethodRefStuck8249261.java:21:9: compiler.err.cant.apply.symbol: kindname.method, p, int, @16, kindname.class, MethodRefStuck8249261, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.incompatible.type.in.conditional: (compiler.misc.not.a.functional.intf: int)))
MethodRefStuck8249261.java:22:19: compiler.err.unexpected.mref
MethodRefStuck8249261.java:23:9: compiler.err.cant.apply.symbol: kindname.method, p, int, @11, kindname.class, MethodRefStuck8249261, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.not.a.functional.intf: int))
MethodRefStuck8249261.java:24:9: compiler.err.cant.apply.symbol: kindname.method, p, int, @11, kindname.class, MethodRefStuck8249261, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.not.a.functional.intf: int))
MethodRefStuck8249261.java:25:12: compiler.err.unexpected.lambda
MethodRefStuck8249261.java:26:12: compiler.err.prob.found.req: (compiler.misc.not.a.functional.intf: boolean)
MethodRefStuck8249261.java:27:9: compiler.err.cant.apply.symbol: kindname.method, p, int, @16, kindname.class, MethodRefStuck8249261, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.incompatible.type.in.conditional: (compiler.misc.not.a.functional.intf: int)))
MethodRefStuck8249261.java:28:20: compiler.err.unexpected.lambda
12 errors

View file

@ -0,0 +1,27 @@
/*
* @test /nodynamiccopyright/
* @bug 8203679
* @summary This is a negative regression test for an AssertionError in DeferredAttr.
* @compile/fail/ref=MethodRefStuckParenthesized.out -XDrawDiagnostics MethodRefStuckParenthesized.java
*/
public abstract class MethodRefStuckParenthesized {
interface I {
String v();
}
interface J {
String v();
}
abstract String v();
abstract void f(I v);
abstract <X extends J> J g(X x);
void test() {
f(g((this::v)));
}
}

View file

@ -0,0 +1,2 @@
MethodRefStuckParenthesized.java:25:5: compiler.err.cant.apply.symbol: kindname.method, f, MethodRefStuckParenthesized.I, MethodRefStuckParenthesized.J, kindname.class, MethodRefStuckParenthesized, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.infer.no.conforming.instance.exists: X, MethodRefStuckParenthesized.J, MethodRefStuckParenthesized.I))
1 error

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8047341
* @summary lambda reference to inner class in base class causes LambdaConversionException
*/
import java.util.List;
import java.util.ArrayList;
class MethodRefToInnerBase {
class TestString {
String str;
TestString(String strin) {
str = strin;
}
}
}
public class MethodRefToInner extends MethodRefToInnerBase {
public static void main(String[] args) {
new MethodRefToInner().run();
}
MethodRefToInner() {
super();
}
void run() {
List<String> list = new ArrayList<>();
list.stream().forEach(TestString::new);
}
}

View file

@ -0,0 +1,24 @@
/*
* @test /nodynamiccopyright/
* @bug 8081271
* @summary NPE while compiling a program with erroneous use of constructor reference expressions.
* @compile/fail/ref=MethodRefToInnerWithoutOuter.out -XDrawDiagnostics MethodRefToInnerWithoutOuter.java
*/
import java.util.List;
import java.util.ArrayList;
class MethodRefToInnerBase {
class TestString {
String str;
TestString(String strin) {
str = strin;
}
}
}
public class MethodRefToInnerWithoutOuter extends MethodRefToInnerBase {
public static void meth() {
List<String> list = new ArrayList<>();
list.stream().forEach(TestString::new);
}
}

View file

@ -0,0 +1,2 @@
MethodRefToInnerWithoutOuter.java:22:31: compiler.err.non-static.cant.be.ref: kindname.variable, this
1 error

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8144673
* @summary Suspect message regarding suitable enclosing instance not being in scope
* @run main MethodRefToLocalClassMethodTest
*/
import java.util.ArrayList;
import java.util.List;
public class MethodRefToLocalClassMethodTest {
public static void main(String[] args) {
new MethodRefToLocalClassMethodTest().foo();
}
public void foo() {
class LocalFoo {
LocalFoo(String in) {
if (!in.equals("Hello"))
throw new AssertionError("Unexpected data: " + in);
}
}
List<String> ls = new ArrayList<>();
ls.add("Hello");
ls.stream().map(LocalFoo::new).forEach(x->{});
}
}

View file

@ -0,0 +1,36 @@
/*
* @test /nodynamiccopyright/
* @bug 8003280
* @summary Add lambda tests
* This is negative test for wrong parameter/return type in method references
* @compile/fail/ref=MethodRef_neg.out -XDrawDiagnostics MethodRef_neg.java
*/
public class MethodRef_neg {
static interface A {void m(Integer i);}
static interface B {void m(String s);}
static interface C {Integer m();}
static interface D {String m();}
static void bar(int x) { }
int foo() {
return 5;
}
static void make() { }
void method() {
A a = MethodRef_neg::bar; //boxing on parameter type is ok
B b = MethodRef_neg::bar; //wrong parameter type, required: String, actual: int
C c = this::foo; //boxing on return type is ok
D d = this::foo; //wrong return type, required: String, actual: int
a = MethodRef_neg::make; //missing parameter
c = MethodRef_neg::make; //missing return type
}
}

View file

@ -0,0 +1,5 @@
MethodRef_neg.java:30:15: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, bar, int, java.lang.String, kindname.class, MethodRef_neg, (compiler.misc.no.conforming.assignment.exists: (compiler.misc.inconvertible.types: java.lang.String, int))))
MethodRef_neg.java:32:15: compiler.err.prob.found.req: (compiler.misc.incompatible.ret.type.in.mref: (compiler.misc.inconvertible.types: int, java.lang.String))
MethodRef_neg.java:33:13: compiler.err.prob.found.req: (compiler.misc.invalid.mref: kindname.method, (compiler.misc.cant.apply.symbol: kindname.method, make, compiler.misc.no.args, java.lang.Integer, kindname.class, MethodRef_neg, (compiler.misc.arg.length.mismatch)))
MethodRef_neg.java:34:13: compiler.err.prob.found.req: (compiler.misc.incompatible.ret.type.in.mref: (compiler.misc.inconvertible.types: void, java.lang.Integer))
4 errors

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8048121
* @summary javac complex method references: revamp and simplify
*
* Make sure NPE check is done even in the convert to Lambda case
*/
public class MethodReferenceComplexNullCheckTest {
public static void main(String[] args) {
F fr = null;
boolean npeFired = false;
try {
IForm frf = fr::doit;
} catch (NullPointerException npe) {
npeFired = true;
} finally {
if (!npeFired) throw new AssertionError( "NPE should have been thrown");
}
}
interface IForm {
void xyz(Object... args);
}
class F {
private void doit(Object... args) { }
}
}

View file

@ -0,0 +1,27 @@
/*
* @test /nodynamiccopyright/
* @bug 8261006
* @summary 'super' qualified method references cannot occur in a static context
* @compile/fail/ref=MethodReferenceInConstructorInvocation.out -XDrawDiagnostics MethodReferenceInConstructorInvocation.java
*/
import java.util.function.Supplier;
public class MethodReferenceInConstructorInvocation {
interface Bar {
default String getString() {
return "";
}
}
static class Foo implements Bar {
Foo() {
this(Bar.super::getString);
}
Foo(Supplier<String> sString) {}
Foo(int i) { this(Bar.super.getString()); }
Foo(String s) {}
}
}

View file

@ -0,0 +1,3 @@
MethodReferenceInConstructorInvocation.java:20:21: compiler.err.cant.ref.before.ctor.called: super
MethodReferenceInConstructorInvocation.java:24:30: compiler.err.cant.ref.before.ctor.called: super
2 errors

View file

@ -0,0 +1,34 @@
/*
* @test /nodynamiccopyright/
* @bug 8318160
* @summary javac does not reject private method reference with type-variable receiver
* @compile/fail/ref=PrivateMethodReferenceWithTypeVarTest.out -XDrawDiagnostics PrivateMethodReferenceWithTypeVarTest.java
*/
import java.util.function.*;
class PrivateMethodReferenceWithTypeVarTest {
class Foo<X> {
X get() { return null; }
}
private String asString() {
return "bar";
}
private String asString2(Object o) {
return "bar";
}
static <T extends PrivateMethodReferenceWithTypeVarTest> Function<T, String> m1() {
return T::asString;
}
static <T extends PrivateMethodReferenceWithTypeVarTest> Function<T, String> m2(T t) {
return t::asString2;
}
static Function<?, String> m2(Foo<? extends PrivateMethodReferenceWithTypeVarTest> foo) {
return foo.get()::asString2;
}
}

View file

@ -0,0 +1,4 @@
PrivateMethodReferenceWithTypeVarTest.java:24:16: compiler.err.report.access: asString(), private, PrivateMethodReferenceWithTypeVarTest
PrivateMethodReferenceWithTypeVarTest.java:28:16: compiler.err.report.access: asString2(java.lang.Object), private, PrivateMethodReferenceWithTypeVarTest
PrivateMethodReferenceWithTypeVarTest.java:32:16: compiler.err.report.access: asString2(java.lang.Object), private, PrivateMethodReferenceWithTypeVarTest
3 errors

View file

@ -0,0 +1,71 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8138667
* @summary Verify that javac emits suitable accessors when a method reference mentions a protected method that would need an accessor
* @run main ProtectedInaccessibleMethodRefTest
*/
import pack.SuperClass;
import java.util.concurrent.Callable;
public final class ProtectedInaccessibleMethodRefTest extends SuperClass {
static String message = "NOT OK";
public void doTest() throws Exception {
new Callable<Void>() {
@Override
public Void call() throws Exception {
final Runnable r = ProtectedInaccessibleMethodRefTest.this::myDo;
r.run();
return null;
}
}.call();
new Callable<Void>() {
@Override
public Void call() throws Exception {
final Runnable r = ProtectedInaccessibleMethodRefTest::myStaticDo;
r.run();
return null;
}
}.call();
}
public void message(String s) {
message = s;
}
public static void main(String[] args) throws Exception {
new ProtectedInaccessibleMethodRefTest().doTest();
if (!message.equals("OK!"))
throw new AssertionError("Unexpected output");
if (!sMessage.equals("OK!"))
throw new AssertionError("Unexpected output");
}
}

View file

@ -0,0 +1,80 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8234729 8242214
* @summary Javac should eagerly change code generation for method references to avert IllegalAccessError in future.
* @compile ProtectedInaccessibleMethodRefTest2.java
* @run main ProtectedInaccessibleMethodRefTest2
*/
import pack.I;
import pack.J;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Function;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
public final class ProtectedInaccessibleMethodRefTest2 extends I {
public static void main(String... args) {
ProtectedInaccessibleMethodRefTest2 m = new ProtectedInaccessibleMethodRefTest2();
m.test(Paths.get("test"));
// Verify that the method references have been folded into lambdas:
Set<String> methodNames = new HashSet<>();
for (Method meth : ProtectedInaccessibleMethodRefTest2.class.getDeclaredMethods()) {
methodNames.add(meth.getName());
}
List<String> expectedMethods =
Arrays.asList("lambda$test$0", "lambda$test$1", "lambda$test$2");
if (!methodNames.containsAll(expectedMethods)) {
throw new AssertionError("Did not find evidence of new code generation");
}
}
void test(Path outputDir) {
Sub c1 = new Sub(this::readFile);
c1.check(outputDir);
Sub c2 = new Sub(ProtectedInaccessibleMethodRefTest2::readFile, this);
c2.check(outputDir);
Sub c3 = new Sub(ProtectedInaccessibleMethodRefTest2::readFile2);
c3.check(outputDir);
}
public class Sub extends J {
Sub(Function<Path,String> fileReader) {
super(fileReader);
}
Sub(BiFunction<ProtectedInaccessibleMethodRefTest2, Path,String> fileReader,
ProtectedInaccessibleMethodRefTest2 instance) {
super(p -> fileReader.apply(instance, p));
}
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8369517
* @summary Compilation mismatch for equivalent lambda and method reference
* @compile/fail/ref=ResultTypeNotBeingCapturedTest.out -XDrawDiagnostics ResultTypeNotBeingCapturedTest.java
* @compile/fail/ref=ResultTypeNotBeingCapturedTest_2.out -XDrawDiagnostics -source 25 ResultTypeNotBeingCapturedTest.java
*/
import java.util.function.Supplier;
class ResultTypeNotBeingCapturedTest {
interface X<T> {
X<T> self();
}
static X<?> makeX() {return null;}
static <R> X<R> create(Supplier<? extends R> supplier) {return null;}
static X<X<?>> methodRef() {
return create(ResultTypeNotBeingCapturedTest::makeX).self();
}
static X<X<?>> lambda() {
return create(() -> makeX()).self();
}
}

View file

@ -0,0 +1,3 @@
ResultTypeNotBeingCapturedTest.java:44:66: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: ResultTypeNotBeingCapturedTest.X<ResultTypeNotBeingCapturedTest.X<compiler.misc.type.captureof: 1, ?>>, ResultTypeNotBeingCapturedTest.X<ResultTypeNotBeingCapturedTest.X<?>>)
ResultTypeNotBeingCapturedTest.java:48:42: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: ResultTypeNotBeingCapturedTest.X<ResultTypeNotBeingCapturedTest.X<compiler.misc.type.captureof: 1, ?>>, ResultTypeNotBeingCapturedTest.X<ResultTypeNotBeingCapturedTest.X<?>>)
2 errors

View file

@ -0,0 +1,4 @@
- compiler.warn.source.no.system.modules.path: 25, (compiler.misc.source.no.system.modules.path: 25)
ResultTypeNotBeingCapturedTest.java:48:42: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: ResultTypeNotBeingCapturedTest.X<ResultTypeNotBeingCapturedTest.X<compiler.misc.type.captureof: 1, ?>>, ResultTypeNotBeingCapturedTest.X<ResultTypeNotBeingCapturedTest.X<?>>)
1 error
1 warning

View file

@ -0,0 +1,320 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test SAM conversion of method references in contexts of assignment, method/constructor argument,
* return statement, array initializer, lambda expression body, conditional expression and cast.
* @compile SamConversion.java
* @run main SamConversion
*/
public class SamConversion {
static int assertionCount = 0;
static interface Foo {
Integer m(int i);
}
static interface Bar {
int m(Integer i) throws MyException;
}
private static void assertTrue(boolean b) {
assertionCount++;
if(!b)
throw new AssertionError();
}
private static int test1(Foo foo) {
return foo.m(1);
}
private static void test2(Bar bar, int result) {
try {
assertTrue(bar.m(1) == result);
} catch (Exception e){
assertTrue(false);
}
}
private static Bar test3(int i) {
switch (i) {
case 0:
return A::method1;
case 1:
return new A()::method2;
case 2:
return A::method3;
case 3:
return new A()::method4;
case 4:
return new A()::method5;
case 5:
return A::method6;
default:
return null;
}
}
/**
* Test SAM conversion of method reference in assignment context
*/
private static void testAssignment() {
Foo foo = A::method1; //static reference, parameter type matching and return type matching
assertTrue(foo.m(1) == 2);
foo = new A()::method2; //instance reference, parameter type unboxing and return type boxing
assertTrue(foo.m(1) == 3);
foo = A::method3; //static reference, parameter type matching and return type boxing
assertTrue(foo.m(1) == 4);
foo = new A()::method4; //instance reference, parameter type unboxing and return type matching
assertTrue(foo.m(1) == 5);
foo = new A()::method5; //instance reference, parameter type unboxing and return type matching
assertTrue(foo.m(1) == 6);
Bar bar = A::method1;
try {
assertTrue(bar.m(1) == 2);
} catch (Exception e) {
assertTrue(false);
}
bar = new A()::method2;
try {
assertTrue(bar.m(1) == 3);
} catch (Exception e) {
assertTrue(false);
}
bar = A::method3;
try {
assertTrue(bar.m(1) == 4);
} catch (Exception e) {
assertTrue(false);
}
bar = new A()::method4;
try {
assertTrue(bar.m(1) == 5);
} catch (Exception e) {
assertTrue(false);
}
bar = new A()::method5;
try {
assertTrue(bar.m(1) == 6);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Test SAM conversion of method reference in method/constructor argument context
*/
private static void testMethodArgument() {
assertTrue(test1(A::method1) == 2);
assertTrue(test1(new A()::method2) == 3);
assertTrue(test1(A::method3) == 4);
assertTrue(test1(new A()::method4) == 5);
assertTrue(test1(new A()::method5) == 6);
test2(A::method1, 2);
test2(new A()::method2, 3);
test2(A::method3, 4);
test2(new A()::method4, 5);
test2(new A()::method5, 6);
}
/**
* Test SAM conversion of method reference in return statement context
*/
private static void testReturnStatement() {
Bar bar = test3(0);
try {
assertTrue(bar.m(1) == 2);
} catch (Exception e) {
assertTrue(false);
}
bar = test3(1);
try {
assertTrue(bar.m(1) == 3);
} catch (Exception e) {
assertTrue(false);
}
bar = test3(2);
try {
assertTrue(bar.m(1) == 4);
} catch (Exception e) {
assertTrue(false);
}
bar = test3(3);
try {
assertTrue(bar.m(1) == 5);
} catch (Exception e) {
assertTrue(false);
}
bar = test3(4);
try {
assertTrue(bar.m(1) == 6);
} catch (Exception e) {
assertTrue(false);
}
bar = test3(5);
try {
bar.m(1);
assertTrue(false);
} catch (MyException e) {
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Test SAM conversion of method reference in cast context
*/
private static void testCast() {
assertTrue(((Foo)A::method1).m(1) == 2);
try {
assertTrue(((Bar)new A()::method2).m(1) == 3);
} catch (Exception e) {
assertTrue(false);
}
}
/**
* Test SAM conversion of method reference in array initializer context
*/
private static void testArrayInitializer() {
Object[] oarray = {"a", 1, (Foo)A::method3}; //last element need a cast
Object[] oarray2 = {"a", 1, (Bar)new A()::method4}; //last element need a cast
Foo[] farray = {A::method1, new A()::method2, A::method3, new A()::method4, new A()::method5};
Bar[] barray = {A::method1, new A()::method2, A::method3, new A()::method4, new A()::method5, A::method6};
}
/**
* Test SAM conversion of method reference in conditional expression context
*/
private static void testConditionalExpression(boolean b) {
Foo f = b ? A::method3 : new A()::method5;
if(b)
assertTrue(f.m(1) == 4);
else
assertTrue(f.m(1) == 6);
Bar bar = b ? A::method1 : A::method6;
if(b) {
try {
assertTrue(bar.m(1) == 2);
} catch (Exception e) {
assertTrue(false);
}
}
else {
try {
bar.m(1);
assertTrue(false);
} catch (MyException e) {
} catch (Exception e) {
assertTrue(false);
}
}
}
/**
* Test SAM conversion of method reference in lambda expression body
*/
private static void testLambdaExpressionBody() {
Foo f = n -> ((Foo)A::method3).m(n);
assertTrue(f.m(1) == 4);
Bar b = n -> { return ((Foo)new A()::method5).m(n); };
try {
assertTrue(b.m(1) == 6);
} catch (Exception e) {
assertTrue(false);
}
}
public static void main(String[] args) {
testAssignment();
testMethodArgument();
testReturnStatement();
testCast();
testArrayInitializer();
testConditionalExpression(true);
testConditionalExpression(false);
testLambdaExpressionBody();
assertTrue(assertionCount == 32);
}
static class MyException extends Exception {}
static class A {
int value = 0;
A() {
}
A(Foo f) {
value = f.m(9);
}
A(Bar b) {
try {
value = b.m(9);
} catch (MyException e){}
}
static Integer method1(int n) {
return n + 1;
}
int method2(Integer n) {
return value == 0 ? n + 2 : n + value;
}
static int method3(int n) {
return n + 3;
}
Integer method4(Integer n) {
return value == 0 ? n + 4 : n + value;
}
Integer method5(Integer n) {
return value == 0 ? new Integer(n + 5) : new Integer(n + value);
}
static int method6(Integer n) throws MyException{
throw new MyException();
}
}
}

View file

@ -0,0 +1,267 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8003280
* @summary Add lambda tests
* Test SAM conversion of method references in combinations of different contexts,
* lambda body types(statement/expression), boxing/unboxing etc, to verify
* SAM conversion being conducted successfully as expected.
* @modules jdk.compiler
*/
import com.sun.source.util.JavacTask;
import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import javax.tools.StandardJavaFileManager;
public class SamConversionComboTest {
enum FInterface {
A("A", "interface A { Integer m(int i); }"),
B("B", "interface B { int m(Integer i); }"),
C("C", "interface C { int m(int i) throws Exception; }");
String interfaceType;
String interfaceDef;
FInterface(String interfaceType, String interfaceDef) {
this.interfaceType = interfaceType;
this.interfaceDef = interfaceDef;
}
}
enum Context {
ASSIGNMENT("#FType f = #MR;"),
METHOD_CALL("void method1(#FType f) { }\n" +
"void method2() {\n" +
" method1(#MR);\n" +
"}"),
CONSTRUCTOR("X x = new X(#MR);"),
RETURN_OF_METHOD("#FType method1() {\n" +
" return #MR;\n" +
"}"),
ARRAY_INITIALIZER("#FType[] oarray = {#MR};"),
LAMBDA_BODY("#FType f = n -> ((#FType)#MR).m(n);"),
CAST("void test() throws Exception { int n = ((#FType)#MR).m(1); }"),
CONDITIONAL_EXPRESSION("#FType f = 2 > 1 ? #MR : null;");
String context;
Context(String context) {
this.context = context;
}
String getContext(FInterface f, MethodReference mr) {
return context.replace("#FType", f.interfaceType).replace("#MR", mr.mrValue);
}
}
enum MethodReference {
METHOD1("X::method1"),
METHOD2("new X()::method2"),
METHOD3("X::method3"),
METHOD4("new X()::method4"),
METHOD5("new X()::method5"),
METHOD6("X::method6"),
METHOD7("X::method7"),
METHOD8("X::method8");
String mrValue;
MethodReference(String mr) {
mrValue = mr;
}
}
enum MethodDef {
METHOD1(" static Integer method1(int n) {\n" +
" return n + 1;\n" +
" }\n", 0),
METHOD2(" int method2(Integer n) {\n" +
" return value == 0 ? n + 2 : n + value;\n" +
" }\n", 1),
METHOD3(" static int method3(int n) {\n" +
" return n + 3;\n" +
" }\n", 2),
METHOD4(" Integer method4(Integer n) {\n" +
" return value == 0 ? n + 4 : n + value;\n" +
" }\n", 3),
METHOD5(" Integer method5(Integer n) {\n" +
" return value == 0 ? new Integer(n + 5) : new Integer(n + value);\n" +
" }\n", 4),
METHOD6(" static int method6(Integer n) throws Exception{\n" +
" throw new Exception();\n" +
" }\n", 5),
METHOD7(" static int method7(String s){\n" +
" return s.length();\n" +
" }\n", 6),
METHOD8(" static String method8(Integer n){\n" +
" return n + \"\";\n" +
" }\n", 7);
String methodStr;
int index;
MethodDef(String ms, int i) {
methodStr = ms;
index = i;
}
MethodReference getMethodReference() {
return MethodReference.values()[index];
}
}
SourceFile samSourceFile = new SourceFile("FInterface.java", "#C") {
public String toString() {
String interfaces = "";
for(FInterface fi : FInterface.values())
interfaces += fi.interfaceDef + "\n";
return template.replace("#C", interfaces);
}
};
String clientTemplate = "class Client {\n" +
" #Context\n" +
"}\n\n" +
"class X {\n" +
" int value = 0;\n\n" +
" X() {\n" +
" }\n\n" +
" X(A a) {\n" +
" value = a.m(9);\n" +
" }\n\n" +
" X(B b) {\n" +
" value = b.m(9);\n" +
" }\n\n" +
" X(C c) {\n" +
" try {\n" +
" value = c.m(9);\n" +
" } catch (Exception e){}\n" +
" }\n\n" +
"#MethodDef" +
"}";
SourceFile clientSourceFile = new SourceFile("Client.java", clientTemplate) {
public String toString() {
return template.replace("#Context", context.getContext(fInterface, methodReference)).replace("#MethodDef", methodDef.methodStr);
}
};
boolean checkSamConversion() {
if(methodDef == MethodDef.METHOD7 || methodDef == MethodDef.METHOD8)//method signature mismatch
return false;
if(context != Context.CONSTRUCTOR && fInterface != FInterface.C && methodDef == MethodDef.METHOD6)
//method that throws exceptions not thrown by the interface method is a mismatch
return false;
if(context == Context.CONSTRUCTOR)
return false;
return true;
}
void test() throws Exception {
System.out.println("\n====================================");
System.out.println(fInterface + ", " + context + ", " + methodReference);
System.out.println(samSourceFile + "\n" + clientSourceFile);
DiagnosticChecker dc = new DiagnosticChecker();
JavacTask ct = (JavacTask)comp.getTask(null, fm, dc, null, null, Arrays.asList(samSourceFile, clientSourceFile));
ct.analyze();
if (dc.errorFound == checkSamConversion()) {
throw new AssertionError(samSourceFile + "\n\n" + clientSourceFile);
}
count++;
}
abstract class SourceFile extends SimpleJavaFileObject {
protected String template;
public SourceFile(String filename, String template) {
super(URI.create("myfo:/" + filename), JavaFileObject.Kind.SOURCE);
this.template = template;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return toString();
}
public abstract String toString();
}
static class DiagnosticChecker implements javax.tools.DiagnosticListener<JavaFileObject> {
boolean errorFound = false;
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
errorFound = true;
}
}
}
FInterface fInterface;
Context context;
MethodDef methodDef;
MethodReference methodReference;
static int count = 0;
static JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
static StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null);
SamConversionComboTest(FInterface f, Context c, MethodDef md) {
fInterface = f;
context = c;
methodDef = md;
methodReference = md.getMethodReference();
}
public static void main(String[] args) throws Exception {
try {
for(Context ct : Context.values()) {
for (FInterface fi : FInterface.values()) {
for (MethodDef md: MethodDef.values()) {
new SamConversionComboTest(fi, ct, md).test();
}
}
}
System.out.println("total tests: " + count);
} finally {
fm.close();
}
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8014023
* @summary When a method reference to a local class constructor is contained
* in a method whose number of parameters matches the number of
* constructor parameters compilation fails
* @compile TreeMakerParamsIsGoofy.java
* @run main TreeMakerParamsIsGoofy
*/
public class TreeMakerParamsIsGoofy {
interface III { }
interface UO {
III m(III x);
}
public static void main(String[] args) {
class BA implements III {
BA(III b) {
}
}
ts(BA::new);
}
static void ts(UO ba) {
}
}

View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package pack;
import java.nio.file.Path;
public class I {
protected String readFile(Path file) {
return file.toString();
}
protected static String readFile2(Path file) {
return file.toString();
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package pack;
import java.nio.file.Path;
import java.util.function.Function;
public class J {
protected final Function<Path,String> fileReader;
public J(Function<Path,String> fileReader) {
this.fileReader = fileReader;
}
protected void checkFile(Path file) {
fileReader.apply(file);
}
public void check(Path file) {
checkFile(file);
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package pack;
public class SuperClass {
public static String sMessage = "Not OK";
protected final void myDo() {
message("OK!");
}
protected static final void myStaticDo() {
sMessage = "OK!";
}
public void message(String s) {
}
}