简体   繁体   English

如何在Java中将方法添加到现有对象?

[英]How can I add method to an existing object in Java?

I'm using a Processing library to build my project in Java. 我正在使用处理库来用Java构建项目。 I use a function that returns me an object of type PShape (which I don't have access to source). 我使用一个函数,该函数返回一个PShape类型的对象(我无法访问源代码)。

I need to make this object of type Shape (a class I designed that extends PShape ). 我需要使这个对象的类型为Shape(我设计了一个扩展PShape )。

How can I make that? 我该怎么做?

Basically I have: 基本上我有:

PShape pShape = loadShape(filename);

Where loadShape is a function I don't have access to source code. loadShape是一个函数的地方,我无法访问源代码。

I want to somehow do: 我想以某种方式做:

class Shape extends PShape {...}

and then 接着

Shape shape = (Shape) loadShape(filename);

But it won't work, once loadShape() will give me a PShape , not a Shape 但这不会起作用,一旦loadShape()给我一个PShape ,而不是一个Shape

How can I make loadShape returns a Shape ? 如何使loadShape返回Shape

Thank you 谢谢

If loadShape() returns a PShape , then it returns a PShape . 如果loadShape()返回PShape ,则返回PShape You can't make it return a subclass of PShape . 您不能使其返回PShape的子类。

Easiest approach would be Shape either copies the PShape into a new instance: eg 最简单的方法是ShapePShape复制到新实例中:

Shape myLoadShape(String filename)
{
    return new Shape(loadShape(filename));
    // Assumes you have a `Shape(PShape)` constructor.
}

or perhaps Shape isn't a subclass, but it contains a PShape data member. 或者Shape不是子类,但是它包含一个PShape数据成员。

class Shape
{
    // No one picked up my C++ syntax goof ;-)
    protected PShape pshape;

    // Using a constructor is just one way to do it.
    // A factory pattern may work or even just empty constructor and a
    // load() method.
    public Shape(String filename)
    {
        pshape = loadShape(filename);
        // Add any Shape specific setup
    }


}

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

相关问题 如何在反应式Java中将新对象添加到现有流中? - How can I add in reactive Java a new Object to an existing stream? 如何在Java中将对象添加到集合中? - How can I add an object into a set in Java? 如何在Java中创建现有对象的数据类型列表 - How can i create list of datatype of an existing object in java 如何装饰现有 Java 对象的方法? - How to decorate an existing Java object's method? java - 如何将对象序列化为Java中同一对象内的方法? - How can I Serialize an object as a method inside the same object in java? Java - 如何将 object 添加到另一个 object 的列表中 - Java - How can I add an object to a list of another object 如何在java流中添加我的方法? - How can I add my method inside java stream? 如何在Java中实现接口的类中添加受保护的方法? - How can I add a protected method to a class implementing an interface in java? 是否可以将Java Portlet添加到现有的Java Web App? - Can I add a java portlet to an existing java Web App? 如何调用Java中存储在arraylist中的特定对象的方法? - How can I call a method of a specific object that is stored in an arraylist in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM