我有一个使用Spymemcached的Java 5应用程序,当我想将Protocol字符串转换为Enum对象时遇到问题。让我们看一下以下内容:
package net.spy.memcached;
...
public class ConnectionFactoryBuilder {
public enum Protocol {
TEXT, BINARY
private Protocol() {
// compiled code
}
}
package mypackage;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws Exception {
String protocolString = "TEXT";
// code 1:
String protocolClassName1 = "net.spy.memcached.ConnectionFactoryBuilder.Protocol";
Class protocolType1 = Class.forName(protocolClassName1);
// The above line throws: Exception in thread "main" java.lang.ClassNotFoundException: net.spy.memcached.ConnectionFactoryBuilder.Protocol
Object protocolEnumObject1 = Enum.valueOf(protocolType1, protocolString);
// code 2:
Class connectionFactoryBuilderClass2 = Class.forName("net.spy.memcached.ConnectionFactoryBuilder");
Field protocolField2 = null;
for (Field f : connectionFactoryBuilderClass2.getDeclaredFields()) {
System.out.print(f.getName() + ", ");
if (f.getName().equalsIgnoreCase("Protocol")) {
protocolField2 = f;
}
}
Class protocolType2 = protocolField2.getType();
Object protocolEnumObject2 = Enum.valueOf(protocolType2, protocolString);
// In this approach, i can not get protocol field in that ConnectionFactoryBuilder class, here are output of getDeclaredFields():
// opQueueFactory, readQueueFactory, writeQueueFactory, transcoder, failureMode,
// initialObservers, opFact, locator, opTimeout, isDaemon, shouldOptimize, useNagle,
// maxReconnectDelay, readBufSize, hashAlg, authDescriptor, opQueueMaxBlockTime,
// timeoutExceptionThreshold, metricType, collector, executorService, authWaitTime, $assertionsDisabled,
}
}
请帮助,谢谢!
答案 0 :(得分:0)
好的,我已经找到解决方法。基本上,枚举协议是ConnectionFactoryBuilder中的嵌套类,因此我需要使用$
来定位它。
这里是已解决的代码:
package mypackage;
public class Test {
public static void main(String[] args) throws Exception {
String protocolString = "TEXT";
// code 1:
// OLD: String protocolClassName1 = "net.spy.memcached.ConnectionFactoryBuilder.Protocol";
String protocolClassName1 = "net.spy.memcached.ConnectionFactoryBuilder$Protocol";
Class protocolType1 = Class.forName(protocolClassName1);
Object protocolEnumObject1 = Enum.valueOf(protocolType1, protocolString);
System.out.println(protocolEnumObject1.getClass());
// class net.spy.memcached.ConnectionFactoryBuilder$Protocol
}
}