Java OO 设计:为什么选择通过接口或对象传递 class 类型?

Java OO Design: why choose to pass a class type over an interface or object?

我看到越来越多的人使用传递 class 类型作为参数。我想知道为什么有人会设计一个应用程序以在接口或对象上使用 class 类型。

原因很简单:

someFunction(someclass.class);

超过:

someFunction(new someclass());

其中 some class 是实现 someInterface 的具体对象。

我会从评论中举个例子:为什么 SpringApplication.run(Application.class, args); 而不是 SpringApplication.run(this, args);

我没有实际使用过 Spring 所以我不确定这是对 Spring 如何调用依赖注入的正确描述,但无论如何它应该可以回答这个问题。

首先,此方法通常从 main 调用。更重要的是,来自 public static void main。那是一个 static 方法,this 在那些方法中不存在。所以它必须是 SpringApplication.run(new Application(), args); 而不是。

但是如果 Application 的构造函数看起来像 public Application(Something dependency1, AnotherThing dependency2, SomethingElse dependency3) 呢?您必须首先制作这些依赖对象中的每一个,并且它们可能也有自己的依赖关系。您最终会得到这个包含数十行创建新对象并将它们传递给更多新对象的构造函数的巨大序列。

SpringApplication.run(Application.class, args); 无论 Application 构造函数是什么样子,它都是一条短线,它专门设计用于为您找出并制作所有这几十个所需的对象。它查看 Application's constructor and sees that list of three arguments, looks at those classes, finds their constructors, looks at those constructors' 参数列表等,直到它有足够的信息为你把整个大混乱拼凑起来。全部来自一个简短的方法调用。要求您传递 Application 的已创建实例而不是 class 会否定这一点,而 class 就是它实际需要的。

还有很多其他事情可以用 class 完成,其中使用实例代替是不必要的,甚至实际上会破坏所需的功能,这只是其中一个例子。