2

他の言語と同様に、オブジェクトを作成し、オブジェクト内のメソッドをオーバーライドできますinitialization。助けてください どうすればいいですか?

例えば:

    public class DemoInitAndOverride {

    public void handleMessage(){}

}

そして別のクラスで

    public class SampleClass {

    public void doSomeThing(){
        DemoInitAndOverride demo = new DemoInitAndOverride(){
            @Override
            public void handleMessage() {
                // TODO Auto-generated method stub
                super.handleMessage();
            }
        };
    }

}
****EDIT:****

可能な解決策と提案をありがとう。解決策を提供するのに役立つ可能性のある要件について、いくつかの詳細を提供することが重要だと思います。

ハンドラーの概念は、ハンドラーを使用して 2 つのスレッドまたは 2 つのメソッド間でメッセージを渡す Android フレームワークに似たものです。以下のコードのデモを参照してください。

UI クラス (ユーザーがボタンをクリックすると、ハンドラを使用してリクエストがプロセッサ クラスにディスパッチされます)

これはデモハンドラです

/**
 * 
 * Used for thread to thread communication.
 * Used for non UI to UI Thread communication.
 *
 */
public class DemoHandler {

    public void handleMessage(Messages message){}

    final public void sendMessage(final Messages message){
        //Calling thread is platform dependent and shall change based on the platform
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    handleMessage(message);
                }
            }
        });
    }
}

これは単純なメッセージクラスです

public class Messages {
    public Object myObject;

    //other hash map (key, values) and get data put data etc
}

これは単純なユーザー インターフェイス クラスのデモ コードです。

public class UIClass {

    public UIClass(){
        //INIT
    }
    void onClick(int id){
        //Some Button is clicked:
        //if id == sendParcel
        //do
        TransactionProcessor.getInstance().sendParcel(handler, "Objects");
    }

    DemoHandler handler = new DemoHandler(){
        public void handleMessage(Messages message) {
            //Inform the UI and Perform UI changes
            //data is present in the messages
        };
    };
}

これはトランザクション プロセッサ クラスのサンプルです。

パブリッククラスTransactionProcessor {

public static TransactionProcessor getInstance(){
    return new TransactionProcessor(); //for demonstration
}
//Various Transaction Methods which requires calling server using HTTP and process there responses:
public void sendParcel(final DemoHandler uiHander, String otherdetailsForParcel){
    //INIT Code and logical code
    //Logical Variables and URL generation
    String computedURL = "abc.com/?blah";
    DemoHandler serverConnectionHandler = new DemoHandler(){
        @Override
        public void handleMessage(Messages message) {
            super.handleMessage(message);
            //Process server response:
            //create a new message for the UI thread and dispatch
            Messages response = new Messages();
            //add details to messages
            //dispatch
            uiHander.sendMessage(response );
        }
    };
    new Thread(new ServerConnection(computedURL, serverConnectionHandler));
}
public void sendEmail(final DemoHandler uiHander, String otherdetailsForEmail){
    //SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
public void sendNotification(final DemoHandler uiHander, String otherdetailsForNotifications){
    //SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}

}

4

2 に答える 2

0

これは厄介なものであり、サブクラスなどを作成することをお勧めします。

これがあなたの答えです。これは基本的に同じですが、実行時です。ご自身の責任で進めてください:

これをインポートします:

#import <objc/runtime.h>

そして、このコードをどこにでも追加します。

- (void)methodName {
    // whatever you want to do in there
}

そしてあなたの機能では:

Class subclass;
// Verifiy that you haven't created it already
subclass = objc_getClass("SampleClassSubclass");
if (!subclass) {
    // Generate a new class, which will be subclass of your SampleClass
    subclass = objc_allocateClassPair(subclass, "SampleClassSubclass", 0);
    // Obtain the implementation of the method you want to overwrite
    IMP methodImplementation = [self methodForSelector:@selector(methodName)];
    // With that implementation, replace the method
    class_replaceMethod(subclass, @selector(methodName), methodImplementation, "@@:");
    // Register the class you just generated
    objc_registerClassPair(subclass);
}

SampleClass *obj = [[subclass alloc] init];
于 2013-01-22T14:55:15.990 に答える
0

Objective-C で行うのはそれほど簡単ではありませんが、これでうまくいくはずです。doSomethingのメソッドをDemoInitAndOverride独自の実装に置き換え、クラスの新しいインスタンスを返します。ただし、これが完了すると、単一のインスタンスだけでなく、クラスのすべての新しいインスタンスに対して新しい実装がそのまま残ることに注意してください。

- (void)doSomething
{
    NSLog(@"self doSomething called");
}

- (DemoInitAndOverride *)createObj
{
    DemoInitAndOverride *obj = [[DemoInitAndOverride alloc] init];

    SEL sel = @selector(doSomething);
    Method theirMethod = class_getInstanceMethod([DemoInitAndOverride class], sel);
    Method myMethod = class_getInstanceMethod([self class], sel);
    theirMethod->method_imp = myMethod->method_imp;
    return obj;
}
于 2013-01-22T14:50:26.740 に答える