我下载了一个学习Java的项目,我找到了修改一些大块代码的有趣方法 我还是Java的新手,我不知道我做的更有效还是更危险...... 语法1是之前的,语法2是我的方法。
语法1:
INSERT INTO freqleeds (id, freq, text) values (14988,2.24,N'欺瞞')
与
语法2:
而不是:
class Person{
TestClass testClass;
TestClass2 testClass2;
//etc...
public Person(){
testClass = new TestClass();
testClass2 = new TestClass2();
//etc...
}
void init(){
testClass.init();
testClass2.init();
//etc...
}
}
此方法使用散列映射并将类存储为对象,并使用枚举作为键。
person.testclass.doThing();
TestClass tc = (TestClass) person.attribute.get(EnumKey.TEST_CLASS);
tc.doThing();
class Person{
public HashMap<EnumKey, Object> attribute;
public Person(){
Class2.sendTasks(this); //sends all classes
}
void init(){
class2.initTasks(this); //inits all
}
}
class Class2{
void sendTasks(Person p)
for (EnumKey ek : EnumKey.values(){
try {
p.attribute.put(ek, ek.handshakeClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
void initTasks(Person p){
for (EnumKey ek : EnumKey.values(){
(TaskClass) tc = p.attribute.get(ek); //NOTE: all stored values (testclass1,2,3,etc) implement the interface TaskClass...
tc.init();
}
}
}
语法2非常简单,因为每次创建新类时我都不必输入TaskClass的所有抽象方法。
我可以创建一个新的枚举字段,剩下的就是为我完成的。
但这种方法好吗?它有效吗?它慢了吗?还是冒险?
答案 0 :(得分:1)
有效吗?它慢了吗?
你正在使用&#34;反射&#34;,所以,是的,那里有一些开销。
另一种可能性是立即构建Hashmap
HashMap<Integer, Object> attribute = new HashMap<>() {{
put(0, new TestClass());
put(1, new TestClass1()) ;
}};
这是一个好方法吗?
这实际上取决于你需要做什么,但它是迭代类似类列表并动态更新其他对象的最短方法,是的。
您可以使用接口和抽象类进一步扩展它。
风险?
不是我知道的。
还有其他方法可以在没有枚举的情况下执行您的操作,例如迭代类路径中的所有文件,但我要说枚举更安全