英文:
Is there a way to run static scope for every subclass once?
问题
我有下面的类:
public abstract class base {
public static String name = "baseClass";
static {
System.out.println(name);
}
}
我认为这段代码会在每个继承这个类的方法中运行,并且会在子类的构造函数之后发生。
例如:
public subclass extends base {
@Override
public static String name = "subclassInfo";
public subclass(){
System.out.println("hello");
}
}
我想在第一次运行时得到:<br>
**hello**<br>
**subclassInfo** <br><br>
在下一次运行中,我将只会得到 **hello** <br><br>
我不想将静态作用域移到子类,我希望它会从基类移到子类,并且只会在第一次调用子类时发生。
英文:
I have the next class :
public abstract class base {
public static String name = "baseClass";
static {
System.out.println(name)
}
}
I that this code will run in every method which extends
this class and that it will happend after the c'tor of the subclass.
for Example for:
public subclass extends base {
@Override
public static String name = "subclassInfo";
public subclass(){
System.out.println("hello")
}
}
I want to get in the first run: <br>
hello<br>
subclassInfo <br><br>
and in the next run I'll get only hello <br><br>
I didn't want to move the static scope to the subclass, I want it will something that move from the base to the subclass and happened only in the first call of the subclass
答案1
得分: 0
为了在创建子类的实例时首次打印子类名称,请执行以下操作:
```lang-java
public abstract class Base {
private static final Map<Class<?>, Boolean> subclasses = new ConcurrentHashMap<>();
{
if (subclasses.putIfAbsent(this.getClass(), Boolean.TRUE) == null)
System.out.println("新的子类:" + this.getClass().getName());
}
}
测试
class Sub1 extends Base {
}
class Sub2 extends Base {
}
class Sub3 extends Base {
}
public class Test {
public static void main(String[] args) {
System.out.println(new Sub3());
System.out.println(new Sub1());
System.out.println(new Sub1());
System.out.println(new Sub3());
}
}
输出
新的子类:Sub3
Sub3@24d46ca6
新的子类:Sub1
Sub1@372f7a8d
Sub1@2f92e0f4
Sub3@28a418fc
英文:
To print the subclass name the first time an instance of the subclass is created, do this:
public abstract class Base {
private static final Map<Class<?>, Boolean> subclasses = new ConcurrentHashMap<>();
{
if (subclasses.putIfAbsent(this.getClass(), Boolean.TRUE) == null)
System.out.println("New subclass: " + this.getClass().getName());
}
}
Test
class Sub1 extends Base {
}
class Sub2 extends Base {
}
class Sub3 extends Base {
}
public class Test {
public static void main(String[] args) {
System.out.println(new Sub3());
System.out.println(new Sub1());
System.out.println(new Sub1());
System.out.println(new Sub3());
}
}
Output
New subclass: Sub3
Sub3@24d46ca6
New subclass: Sub1
Sub1@372f7a8d
Sub1@2f92e0f4
Sub3@28a418fc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论