Bug 77212

Summary: [1.5][enum] declared enum type .valueOf(String) throws ArrayIndexOutOfBoundsException
Product: [Eclipse Project] JDT Reporter: jp fielding <jp.fielding>
Component: CoreAssignee: Olivier Thomann <Olivier_Thomann>
Status: VERIFIED FIXED QA Contact:
Severity: normal    
Priority: P3    
Version: 3.1   
Target Milestone: 3.1 M3   
Hardware: PC   
OS: Linux   
Whiteboard:
Attachments:
Description Flags
Apply on HEAD none

Description jp fielding CLA 2004-10-28 12:28:52 EDT
a declared enum type 

public enum RuleType{ AVAILABLE, MANDATORY }

has the generated method RuleType.valueOf(String)

this call chokes with an ArrayIndexOutOfBoundsException when called with valid
values:

RuleType.valueOf(RuleType.AVAILABLE.name())
Comment 1 Frederic Fusier CLA 2004-10-28 12:39:30 EDT
The exception happens at runtime.

public class X {
	public enum RuleType{ AVAILABLE, MANDATORY }
	public static void main(String[] args) {
		System.out.println(RuleType.valueOf(RuleType.AVAILABLE.name()));
	}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
	at X$RuleType.valueOf(X.java:1)
	at X.main(X.java:5)
Comment 2 Olivier Thomann CLA 2004-10-28 16:40:46 EDT
Created attachment 15457 [details]
Apply on HEAD

With this patch the code works.
Three errors found:
The code is doing a reverse loop on the values array, but it doesn't take:
- length - 1 for the first index
- doesn't get the name() of the current entry
- stop one two earlier (gt instead of ge)
Comment 3 Olivier Thomann CLA 2004-10-28 16:41:27 EDT
I get:

C:\tests_sources>java X
AVAILABLE
Comment 4 Olivier Thomann CLA 2004-10-28 16:56:48 EDT
We could also use the method:
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                            String name)

defined on java.lang.Enum.
Comment 5 Philipe Mulet CLA 2004-10-28 17:29:03 EDT
Pls also update the comment in front:
//	static X valueOf(String name) {
//		X[] values;
//		for (int i = (values = $VALUES).length; --i >= 0;) {
//			X value;
//			if (name.equals(value = values[i].name())) return value;
//		}
//		throw new IllegalArgumentException(name);
//	}		
Comment 6 Olivier Thomann CLA 2004-10-28 17:51:33 EDT
Fixed and released in HEAD.
Regression test added in EnumTest.
Comment 7 David Audel CLA 2004-11-04 04:25:25 EST
Verified for 3.1M3 with build I20041102