public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("ENTITIES")){
System.out.println("entities factory created with out calling");
return new LoadEntityFactory();
}
elseif(choice.equals.IgnoreCase("UNITS"))
return new UnitFactory();
}
}
加载实体类
public class LoadEntityFactory extends AbstractFactory {
@Override
public loadEntities getLoadEntity(String entity) {
if(entity==null){
return null;
}else if (entity.equalsIgnoreCase("categories")) {
return new LoadCategoryEntity();
}
else if (entity.equalsIgnoreCase("books")) {
return new LoadBookEntity();
}
else if (entity.equalsIgnoreCase("author")) {
return new LoadAuthorEntity();
}
else if (entity.equalsIgnoreCase("publisher")) {
return new LoadPublisherEntity();
}
return null;
}
}
现在我的问题是,当我调用 FactoryProducer.getFactory("entities") 时,它会创建三个对象吗?当类加载到 JVM 中时,会创建两个对象(实体和单元),而当我调用静态方法时,会创建一个对象吗?
最佳答案
所有方法只有在被调用时才会执行。不在类加载上。如果您想在加载类时执行某些操作,请使用静态初始化 block 。
When I call FactoryProducer.getFactory("entities").Will it create three objects, two objects(entity and unit) will be created when class is loaded into JVM and one when I call the static method?
- 方法
getFactory
仅在被调用时才会执行。不是在类加载时。 - 当您传递
“entities”
时,第一个if
条件将为true,并且在使用调用时
LoadEntityFactory
将被实例化新的LoadEntityFactory else
条件不会成立,因此不会调用new UnitFactory
并且不会创建UnitFactory
对象。
关于java - 静态方法在类加载时是否创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19048225/