简体   繁体   English

使用Java注释将类替换为派生类

[英]Replace class with derived class using Java annotations

Say I extend a Java class like java.util.List to create a custom class called MyList ... Is there any way if my peers write code using List , I can convert it into MyList during compilation/runtime? 假设我扩展了java.util.List类的Java类以创建一个名为MyList的自定义类...如果我的同辈使用List编写代码,可以在编译/运行时将其转换为MyList吗?

ie If they have something like: 即,如果他们有类似的东西:

List groceryList = new List();

it should be compiled/run like: 它应该像这样编译/运行:

MyList groceryList = new MyList();

I know annotations can do something of this sort. 我知道注释可以做这种事情。 Is it possible to use them in this case? 在这种情况下可以使用它们吗? If yes, how? 如果是,怎么办?

This is known as downcasting . 这称为垂降

The short answer is that if they created the object with the new command, such as in your example, then no, you will not be able to cast it. 简短的答案是,如果他们使用new命令创建了对象(例如您的示例中的对象),则否,那么您将无法投射它。

What you can do, is define a constructor in MyList class that accepts the object-to-be-converted as a parameter and uses it to create a new object. 您可以做的是在MyList类中定义一个构造函数,该构造函数接受要转换的对象作为参数,并使用它来创建新对象。 The list is a bit special because you can create new lists from existing ones . 该列表有点特殊,因为您可以从现有列表中创建新列表 For example: 例如:

public MyList (List oldList)
{
    super(oldList); //this will copy the objects of the list to your custom list
    //But you could do any other operations to create the new object from the parameter(s)
    ...
}

and use it as 并用作

MyList groceryList = new MyList(oldList);

尽管在Java中进行向上转换通常是安全的,但除非确实需要,否则在Java中进行向下转换不是您应该经常使用的方法,因为子类可能不支持超类可以支持的某些属性或方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM