Java:返回类(不是实例)

问题描述:

是否可以在静态方法中返回一个类?我会解释......

Is it possible to return in a static method a class? I will explain...

我有:

public class A { public static void blah(){} }
public class B { }

I想要在B中创建一个静态方法,返回 A 。所以你可以这样做:

I want to create a static method in B witch returns A. So you can do:

A.blah();

B.getA().blah();

这样,无需创建 A的实例 。只需使用静态方法。

This, without creating an instance of A. Just use it static methods.

这可能吗?

这是@ irreputable的答案的反驳:

This is a rebuttal of @irreputable's answer:

public class B { 
    public static A getA(){ return null; }
}

B.getA().blah(); //works!

它有效,但可能不是你所期望的,当然也不是有用的办法。我们将其分为两部分:

It "works", but probably not in the sense that you expect, and certainly not in a useful way. Let's break this down into two parts:

A a = B.getA();
a.blah();

第一个语句返回一个(在这种情况下为null)实例 A ,第二个语句忽略该实例并调用 A.blah()。所以,这些陈述实际上相当于

The first statement is returning a (null in this case) instance of A, and the second statement is ignoring that instance and calling A.blah(). So, these statements are actually equivalent to

B.getA();
A.blah();

或(假设 getA()是副作用免费),只是简单

or (given that getA() is side-effect free), just plain

A.blah();

以下是一个更清楚地说明这一点的例子:

And here's an example which illustrates this more clearly:

public class A {
   public static void blah() { System.err.println("I'm an A"); }
}

public class SubA extends A {
   public static void blah() { System.err.println("I'm a SubA"); }
}

public class B { 
   public static A getA(){ return new SubA(); }
}

B.getA().blah(); //prints "I'm an A".

......这(我希望)说明了为什么这种方法无法解决OP的问题。

... and this (I hope) illustrates why this approach doesn't solve the OP's problem.