JDK-5073043 : Generic class vs Foreach causes compile error
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 5.0
  • Priority: P3
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_2000
  • CPU: x86
  • Submitted: 2004-07-12
  • Updated: 2004-07-12
  • Resolved: 2004-07-12
Related Reports
Relates :  
Description

Name: jl125535			Date: 07/12/2004


FULL PRODUCT VERSION :
java version "1.5.0-beta3"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-beta3-b57)
Java HotSpot(TM) Client VM (build 1.5.0-beta3-b57, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows 2000 [Version 5.00.2195]
Microsoft Windows XP [Version 5.1.2600]

A DESCRIPTION OF THE PROBLEM :
Uses a generic class "myClass< T >" with a containing function that returns a generic list causes a compile error on the foreach claiming that it is trying to assign an Object to a Throwable in this case. The generic T is not used anywhere in the class. See example.

Produced "Incompatible type" error.

Removing the generic from the class stops the compile error from happening.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
javac -source 1.5 Test.java

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
No compile error


ACTUAL -
"Incompatible types. Found java.lang.Object. Required java.lang.Throwable"

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Test.java:11: incompatible types
found   : java.lang.Object
required: java.lang.Throwable
        for ( Throwable t : testThrows.getExceptions() )
                                                    ^
1 error


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
import java.util.List;
import java.util.ArrayList;

public class Test
{
    public static void main( String[] args )
    {
        TestThrows testThrows = new TestThrows();

        // compile error on the next line
        for ( Throwable t : testThrows.getExceptions() )
        {
            t.toString();
        }
    }

    static class TestThrows< T >
    {
        public List< Throwable > getExceptions()
        {
            List< Throwable > exceptions = new ArrayList< Throwable >();
            return exceptions;
        }
    }
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Removing the generic ("< T >") from the TestThrows class removes the compiler error.
(Incident Review ID: 285197) 
======================================================================

Comments
PUBLIC COMMENTS ...
13-07-2004

EVALUATION Since you are using the raw type TestThrows in the loop, all of its members are erased. In particular, the return type of getExceptions() in the raw type is a raw List. Therefore, the compiler is correct. ###@###.### 2004-07-12
12-07-2004