logo
down
shadow

Tips: wrapping class in java in order to add new methods


Tips: wrapping class in java in order to add new methods

By : Hukunooy Hukunooy
Date : November 22 2020, 12:01 PM
I think the issue was by ths following ,
First, your private wrappedSequence = null; has no type. I suppose you meant private Sequence wrappedSequence = null;
code :
public interface Sequence {
    public void methodOne();
    public int methodTwo();
}

public abstract class AbstractSequence  implements Sequence {


    public SequenceWrapper( ){  }

    public void methodOne(){
        //basic behavior here
    }

    public int methodTwo(){
         //basic behavior here

    }
}

public class ConcreteSequence extends AbstractSequence {
    public ConcreteSequence ( ){
         super( );
    }

    // Just an example
    public int addMethodOne(){
         int a =  methodTwo();
         return a + 3;
    }        
}


public class ConcreteSequenceTwo extends AbstractSequence {
    public ConcreteSequenceTwo( ){
         super( );
    }

    public int addMethodTwo(){
         int a =  methodTwo();
         return a + 30;
    }
}


Share : facebook icon twitter icon
Java reflection: Is the order of class fields and methods standardized?

Java reflection: Is the order of class fields and methods standardized?


By : PBL
Date : March 29 2020, 07:55 AM
Hope this helps According to the documentation:
getFields()
python parent class 'wrapping' child-class methods

python parent class 'wrapping' child-class methods


By : Rupert Connelly
Date : March 29 2020, 07:55 AM
help you fix your problem Don't use inheritance here
Invert your design. Instead of a parent-child implementation which is a "is-a" relationship why not just have a composition so you get a "has-a" relationship? You could define classes which implement the methods you'd like while your previous parent class would be instantiated with those implementation specific classes.
code :
class MyClass:
    def __init__(self, impl)
        self.impl = impl
    def run(self,var):
        print "prepare"
        impl.runImpl(var)
        print "I'm done"

class AnImplementation:
    def runImpl(self,var):
In java, can one create a fluent extensible class hierarchy with methods that can be invoked in any order?

In java, can one create a fluent extensible class hierarchy with methods that can be invoked in any order?


By : Rita Figueiredo
Date : March 29 2020, 07:55 AM
may help you . The answer (to my surprise and satisfaction) is YES. I answered this question myself: You can do this with a little work if the method invocations return instances of the class in question (see chainable below). I also found an even easier way do this if you can edit the top level source:
In the top level class (A):
code :
protected final <T> T a(T type) {
    return type
}
C c = new C();
//Any order is fine and you have compile time safety and IDE assistance.
c.setA("a").a(c).setB("b").a(c).setC("c");
import static java.lang.System.out;

public class AATester {
    public static void main(String[] args){

        //Test 1:
        for(int x: new int[]{ 0, 1, 2 } ){
            A w = getA(x);
            //I agree this is a nasty way to do it... but you CAN do it.
            Chain.a(w.setA("a1")).a(w instanceof C ? ((C) w).setC("c1") : null );
            out.println(w);
        }

        //Test for WAY 2: Hope this wins Paul Bellora's approval 
        //for conciseness, ease of use and syntactic sugar.
        C c = new C();
        //Invoke methods in any order with compile time type safety!
        c.setA("a2").a(c).setB("b2").a(c).set("C2");
        out.println(w);

        //Example 3, which is Example 1, but where the top level class IS known to be a "C"
        //but you don't have access to the source and can't add the "a" method to the 
        //top level class.  The method invocations don't have to be as nasty as Example 1.
        c = new C();
        Chain.a(c.setA("a3")).a(c.setB("b3")).a(c.setC("c3"));//Not much larger than Example 2.
        out.println(w);
    }
    public static getA(int a){//A factory method.
        A retval;//I don't like multiple returns.
        switch(a){
            case 0:  retval = new A(); break;
            case 1:  retval = new B(); break;
            default: retval = new C(); break;
        }
        return retval;
    }
}
public class A {
   private String a;
   protected String getA() { return a; }

   //WAY 2 - where you have access to the top level source class.
   protected final <T> T a(T type) { return type; }//This is awesome!       

   protected A setA(String a) { this.a=a; return this; }//Fluent method
   @Override
   public String toString() {
      return "A[getA()=" + getA() + "]";
   }
}
public class B extends A {
   private String b;
   protected String getB() { return b; }
   protected B setB(String b) { this.b=b; return this; }//Fluent method
   @Override
   public String toString() {
      return "B[getA()=" + getA() + ", getB()=" + getB() + "]\n  " 
      + super.toString();
  }
}
public class C extends B {
   private String c;
   protected String getC() { return c; }
   protected C setC(String c) { this.c=c; return this; }//Fluent method
   @Override
   public String toString() {
      return "C [getA()=" + getA() + ", getB()=" + getB() + ", getC()=" 
             + getC() + "]\n  " + super.toString();
   }
}
/**
 * Allows chaining with any class, even one you didn't write and don't have 
 * access to the source code for, so long as that class is fluent.
 * @author Gregory G. Bishop ggb667@gmail.com (C) 11/5/2013 all rights reserved. 
 */
public final class Chain {
   public static <K> _<K> a(K value) {//Note that this is static
      return new _<K>(value);//So the IDE names aren't nasty
   }
}
/** 
 * An instance method cannot override the static method from Chain, 
 * which is why this class exists (i.e. to suppress IDE warnings, 
 * and provide fluent usage). 
 *
 * @author Gregory G. Bishop ggb667@gmail.com (C) 11/5/2013 all rights reserved.
 */
final class _<T> {
   public T a;//So we may get a return value from the final link in the chain.
   protected _(T t) { this.a = t }//Required by Chain above
   public <K> _<K> a(K value) {
      return new _<K>(value);
   }
}
A [get(A)=a]
B [get(A)=a, getB()=null]
  A [getA()=a]
C [getA()=a, getB()=null, getC()=c)]
  B [get(A)=a, getB()=null]
  A [get(A)=a]
Book b = null; 
Publisher p = null; 
List books = null; 
String id = "Elric of Melnibone";

books = Chain.a(b = findBook(id)).a(b != null ? p = b.getPublisher() : null)
                                 .a(p != null ? p.getPublishedBooks(): null).a;

out.println(books==null ? null : Arrays.toString(books.toArray()));
Book b = null; 
Publisher p = null; 
List books = null; 
String id = "Elric of Melnibone";

b = findBook(id);
Array[] books = null;
if( b != null ) {
    p = b.getPublisher();
    if(p != null) {
        books = p.getPublishedBooks();
    }
} 

out.println(books==null ? null : Arrays.toString(books.toArray()));
Java order of class fields and methods in singleton

Java order of class fields and methods in singleton


By : Lance Tipton
Date : March 29 2020, 07:55 AM
Hope this helps You have to understand what is going on when a class is being created. When a class is created, its static members are also created, line by line.
I think the real issue is that you declared SomeDataSource as static, when it should not be. However, to explain what is causing the issue, lets keep looking at it.
code :
private static SomeDataSource sDS = null;
private static SomeConnectionPool sCP = new SomeConnectionPool ();
public class SomeConnectionPool
{
   private static final Logger log = Logger.getLogger (SomeConnectionPool.class.getName());
   private static SomeDataSource sDS = new SomeDataSource (config);
   private static SomeConnectionPool sCP = new SomeConnectionPool ();

   private SomeConnectionPool ()
   {
     // Configure DataSource, connect to DB
   }
public class SomeConnectionPool
{
   private static final Logger log = Logger.getLogger (SomeConnectionPool.class.getName());
   private static SomeConnectionPool instance = new SomeConnectionPool ();
   private SomeDataSource sDS = null;

   private SomeConnectionPool ()
   {
     // Configure DataSource, connect to DB
      this.sDs = new SomeDataSource (config);
   }
   public static SomeConnectionPool getInstance ()
   {
     return instance;
   }
   public SomeDataSource getDataSource ()
   {
      return this.sDs;
   }
Wrapping a class without repeating all methods in Java

Wrapping a class without repeating all methods in Java


By : Ali Abdul
Date : March 29 2020, 07:55 AM
Hope that helps Your IDE handles this kind of tasks for you.
For example, you could add a member variabile of type MyService inside MyTenantOrientedService and, on Eclipse, right-click on MyTenantOrientedService, then click on "Source -> Generate Delegate Methods"
Related Posts Related Posts :
  • Java Application Client Freezed with an JNIWrapper exception
  • How do i make sure that the ID of object im adding to array doesn't exist without getting nullpointerexception?
  • Code Coverage for every (different) input data
  • Is there a function in java which helps to format and return the formatted date as output?
  • How to reuse Android-Handler after removing callbacks
  • What's wrong with this solution of coin change problem?
  • Showing error while inserting User in room database
  • Feign : file upload configuration
  • How to differentiate row name by column heading, if there are multiple rows available
  • Change behavior without modifying base class
  • Why I have Permission denied on a file located in /data/user_de/
  • Calculate date range and return true
  • How to draw multiple points on imageview in android java
  • How to display ListView in Reverse Order (Latest First on Top)?
  • separate the file in fileinputstream input and insert the data into oracle tables
  • How to append a column of data to the end of text file
  • Return ArrayList item instead of boolean
  • Remove few elements from a Map of String to List for a specific key
  • Load more not working after swipe to refresh
  • Does a 'z' in a datetime String have different outputs in different locales?
  • What I have to modifiy for the 64-bit requirement?
  • Updating and deleting from DB using JpaRepository
  • Incompatible types with new class?
  • How to convert nested for loop with extra command to java stream
  • Set cookies on successful OAuth2 Authentication in Spring Security OAuth2 implementation
  • Groovy - Regex match the string with last char numbers
  • Problem when splitting an item from array list into a string array
  • Check link to know if it is image or not in android/java
  • Scala JSR223 script using JMeter/Java context
  • I executed selenium code but an error is appearing
  • Why are WebMvcConfigurer override methods not working?
  • JPA Criteria Specification for ManyToMany
  • Mongodb Timestamp Output Format returns "$numberLong" Object when I want to get the unix time in millis
  • Is SecureRandom.ints() secure?
  • Using advanced search operators in sending query to saerch engine using restful API
  • How I can get image Uri from gallery for a long time?
  • How to send List value in Request Body to Rest Api
  • How to get the processing kafka topic name dynamically in Flink Kafka Consumer?
  • How to pass function as parameter from java to kotlin method?
  • Java SWT - Adding buttons to shell
  • How "site" can be input for the viewer? What is "site" in Eclipse API?
  • "unreported exception IOException; must be caught or declared to be thrown". Have a look on the coding
  • Google Anlytics in Java: AnalyticsService "application name"
  • how to handle error when there is no coordinate to show in arraylist?
  • When should I use Factory<T> instead of Provider<T>
  • Why is assigning 'int constant -> byte variable' valid, but 'long constant -> int variable' is not?
  • Adding Service layer to Web APP to display DB contents on a jsp
  • How to fix java.awt.HeadlessException in Jenkins on Linux
  • Calling custom mongoDB query with spring data fails
  • Reusing visual class created with WindowBuilderPro
  • Is it allowed to have any logging on Android Public release?
  • Cannot pass java.lang.long to com.jacob.activeX.ActiveXComponent.invoke
  • Is initialization of objects Thread Safe in Java
  • Save as java file
  • JasperReports: filling a report throws an exception “TargetInvocationException”
  • How to insert about 500.000 data rows in table efficiently
  • Android Soundboard only one sound at a time
  • Inner forEach in forEach jstl error
  • Finding the key of HashMap which holds the lowest integer value
  • Time Difference with UTC java
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org