Downcasting instance from external Jar - java

//Class defined in external jar
class A{
many methods...
public getId() {};
}
//I want to extends this class and overwrite single method
class MyA extends A{
private int myId;
public getId() {return myId};
}
void main ()
{
A a = Factory.getA(); //External class create the instance
MyA mya = (MyA)a; //runtime Error!! I want to convert A to myA
}
Hi,
I want to extends an instance which I get from external Jar and overwrite a single method getId(). I don't control the creation of the instance so the only solution I got was to pass it to my constructor and init all members manually, example here:
class MyA extends A{
private int myId;
public MyA(A a, int myId)
{
this.myId = myId;
//init all other methods from a.? to this.?
this.setXXX(a.getXXX());
this.setYYY(a.getYYY());
....many methods...
}
public getId() {return myId};
}
Is there a better way?

MyA mya = (MyA)a; //runtime Error!! I want to convert A to myA
Is a an instance of MyA?? You can not convert if it is not an instance of MyA. you get java.lang.ClassCastException.

Rather than getting all data from A in the constructor of MyA (and thus reimplementing it completely), create an Adapter, change the methods you need and in the rest just pass the calls to the original instance of A:
class MyA extends A{
private A adaptee;
private int myId;
public MyA(A adaptee, int myId)
{
this.adaptee = adaptee;
this.myId = myId;
}
// Override the method you need to
#Override
public getId() {return myId};
...
// Override the rest of the methods so they call the adaptee.
#Override
public X getXXX() {
return a.getXXX();
}
#Override
public void setXXX(X x) {
a.setXXX(x);
}
...
}
Then, of course, use it as:
A a = new MyA(Factory.getA(), myId);
... a.getId();

Related

Common method to set values of the fields for the parent class

I have a Response class which contains n number of fields and there are multiple classes which extend my Response class. In every method I need to set fields of the response class along with my sub class fields, instead i want to create a common method which sets all the fields of my parent class and returns me the sub class.
Parent Class
class Response{
private String a;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
}
Sub Class 1
class Custom extends Response{
private String b;
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
Sub Class2
class Custom1 extends Response{
private String c;
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}
method 1
public Custom setFields(String aValue,String bValue){
Custom c = new Custom();
c.setA(aValue);
c.setB(bValue);
return c;
}
method 2
public Custom1 setFields(String aValue,String cValue){
Custom1 c1 = new Custom1();
c1.setA(aValue);
c1.setC(cValue);
return c1;
}
I want to create a method which sets the value of the fields belonging to the Response class and return me the same class object Custom or Custom1 respectively
Ex:
Custom c = setResponseValue(aValue); OR
Custom1 c1 = setResponseValue(aValue);
Methods something like
public Custom/Custom1 setResponseValue(String value){
/**
Sets the value
**/
return Custom/Custom1;
}
Please help as i need to do the same thing over and over again.Problem increase as the no of fields increase in the response class.
Since you want to return a child class with the value of the parent set, you could have your child class constructor with an input value and use it to set the value on the parent.
public class Response {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class Child extends Response {
public Child(String value) {
setValue(value);
}
}
And then use it like this:
Child childResponse = new Child("hey");
Update:
I am not sure I understand exactly what you mean, but if you do not want to set the value in the constructor, and you don't want to set the value for an existing child object, maybe you need a cloned object returned with this new value. Make sure your class supports the Cloneable interface and:
public Child cloneAndSetValue(String value) throws CloneNotSupportedException {
Child c = (Child) this.clone();
c.setValue(value);
return c;
}
If you want setResponseValue to be outside of your pojo classes then you need to tell it how to create a specific subclass. Here is how you can accomplish it with Java lambdas and generics:
Custom c1 = setResponseValue( Custom::new, "a1" );
Custom1 c2 = setResponseValue( Custom1::new, "a1" );
public static <T extends Response> T setResponseValue(Supplier<T> s, String value){
T result = s.get();
result.setA(value);
return result;
}

access variable of upper/wrapper class

I'm a beginner at Java so I don't know if what I'm trying to access is an upper/wrapper class. Basically, I have three classes, A, B and C.
CLASS A.java
public class A{
private String aName;
private B objectB;
}
CLASS B.java
public class B{
private String bName;
private C objectC;
}
CLASS C.java
public class C{
private String cName;
}
Basically, I have a Class A, which has an object of Class B, which in turn has an Object of class C.
I have an instance of an object of class C. How do I access the variables bName and cName from this instane of object C?
Why don't you use getter & setter method for accessing variable bName from instance of c. you can not directly access them as they are private.
"CLASS B.java"
public class B{
private String bName;
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
private C objectC;
}
You can directly access "cName" variable as this variable is the belong to same obejct of c which you are using to get bName.
The easiest solution for getting access to the instance of Class B from Class C would be to add a reference to B in C:
Class C
public class C {
private String cName;
private B bObj;
}
And then use getters and setters in class B:
Class B
public class B {
private String bName;
private C cObj;
public String getBName() {
return bName;
}
public void setBName(String newName) {
this.bName = newName;
}
}
However, do remember that this leads to a circular dependency, which usually is a code smell (it may be OK in this situation though, depending on the overall class hierarchy).
The better option would be to implement the Observer pattern between the classes:
Class C
public class C {
private String cName;
private List<Observers> observers; //if you only need one instance, then
//switch out for a single interface reference
public void requestWrapperName () {
List<String> names = new ArrayList<>();
for(observer: observers) {
names.add(observer.requestName());
}
// code to do what you want with wrapper name
...
}
public void addObserver(Observer observer) {
observers.add(obsersver);
}
}
Observer interface
public interface Observer {
String requestName();
}
Class B
public class B implements Observer {
private String bName;
private C cObj;
// Observer method
public String requestName() {
return bName;
}
}
Now, when you have the instance of C in class B, you can just inject B as an observer into C with cObj.addObserver(this); and then request B's name with the method requestWrapperName();. Thus avoiding having associations both ways :)

Always execute method after constructor in Java

I have a situation where I always need to run a certain bit of code that depends on the object itself
public abstract class A{
public A(X x){
//init A stuff
x.getAList("stuff").add(this);
x.getAList("otherstuff").add(this);
}
}
public class B extends A{
public B(X x){
super(x);
//init B stuff
}
}
public class C extends A{
public C(X x){
super(x);
//init C stuff
x.getAList("otherstuff").remove(this);
x.getAList("morestuff").add(this);
}
}
public class SomeClass{
private X someX;
public A somefunc(boolean b){
if(b){
return new B(someX);
}else{
return new C(someX);
}
}
}
The problem is the following. In this example I use this in the constructor. If another thread tries to access the object through someX.getAList, it could cause that thread to get access to the object before the constructor has ended.
You could make it so that the object gets added to the AList by somefunc
public class SomeClass{
private X someX;
public A somefunc(boolean b){
A a;
if(b){
a = new B(someX);
someX.getAList("stuff").add(a);
someX.getAList("otherstuff").add(a);
}else{
a = new C(someX);
someX.getAList("stuff").add(a);
someX.getAList("morestuff").add(a);
}
return a;
}
}
The problem is that B's and C's could also be instantiated elsewhere and that everytime a B or C is created they would need to be added in that specified way. I don't want adding the object to the AList to be the responsibility of the user, but of the class. I also don't want the user to have to call an init function that does this for them. On the other hand, I don't want any concurrency issues.
Is there a way or a pattern that makes it possible to implement this?
Golang has something like defer that lets you run a piece of code after the function/method/constructor is done.
Make a Factory-Method for the super and subclass instead and make the constructors private, forcing everyone who wants an instance to use the factory method. A factory method is a method that returns a completely constructed instance. Once the instance is completely constructed (after the constructor was called in the factory method) add the instance to the list, that way no thread can get hold of a incomplete/non-finalized instance.
The point of the Factory-Method is to strictly isolate all the initialisation code from any non-initialisation code, to avoid access to and exposure of uninitialised fields. Also it can serve as a selector for users, automatically returning a suitable (sub-)type, without having to be specified.(Interesting design-patterns)
abstract class A{
protected A(){
//constructor code goes here
}
public void afterFinalisation(final X x) {
x.getAList("stuff").add(this);
x.getAList("otherstuff").add(this);
}
}
class B extends A{
protected B(){
super();
//constructor code goes here
}
public static B create(final X x) {
final B returnValue = new B();
returnValue.afterFinalisation(x);
return returnValue;
}
}
class C extends A{
protected C(){
super();
//constructor code goes here
}
#Override
public void afterFinalisation(final X x) {
super.afterFinalisation(x);
x.getAList("otherstuff").remove(this);
x.getAList("morestuff").add(this);
}
public static C create(final X x) {
final C returnValue = new C();
returnValue.afterFinalisation(x);
return returnValue;
}
}
class SomeClass{
private final X someX = new X();
public A somefunc(final boolean b){
if(b){
return B.create(this.someX);
}else{
return C.create(this.someX);
}
}
}
The credit for the constructor code goes to coolcats iteration of my answer, I was trying to avoid putting code into the protected constructors and worked with a init() method instead, which required a big unelegant-workaround for final fields.
By taking a few design decisions from HopfullyHelpful I end up with liking the following design best:
public abstract class A{
protected A(X x){
//constructor with all inits
}
protected A publish(X x) {
x.getAList("stuff").add(this);
x.getAList("otherstuff").add(this);
return this;
}
}
class B extends A{
protected B(X x){
super(x);
//constructor with all inits
}
protected B publish(X x) {
super.publish(x);
return this;
}
public static B create(X x) {
return new B(x).publish(x);
}
}
class C extends A{
protected C(X x){
super(x);
//constructor with all inits
}
protected void publish(X x) {
super.publish(x);
x.getAList("otherstuff").remove(this);
x.getAList("morestuff").add(this);
return this;
}
public static C create(X x) {
return new C(x).publish(x);
}
}
class SomeClass{
private X someX;
public A somefunc(boolean b){
if(b){
return B.create(this.someX);
}else{
return C.create(this.someX);
}
}
}

What's the correct way to "share" variables between methods in different classes?

I'm trying to share variables between methods in different classes, but I don't know if I'm doing this in the correct way. Basically when I wanna use the variables on method2 I have to "transport" them throught method1 to method2 from the Class A, just take a look at the example because I don't know how to explain this properly.
Is this the correct way to do it? Because sometimes I do this over an over through methods and it looks ugly.
Example:
public class A {
int var1, var2, var3;
B b = new B();
b.method1(var1, var2, var3);
}
public class B {
public void method1(int var1, int var2, int var3){
//doSomething
method2(var2, var3);
}
public void method2(int var2, int var3){
//doSomething
}
}
Btw, is there any community where code reviews are done? I'm pretty new to code and I'm afraid that I'm creating code that isn't effective.
Thanks for the help! :)
Use getters and setters to get variable of Class A from B as following..
public class A {
private int var1, var2, var3;
public int getVar1(){
return var1;
}
public void setVar1(int var1){
this.var1 = var1;
}
public int getVar2(){
return var2;
}
public void setVar2(int var2){
this.var2 = var2;
}
public int getVar3(){
return var3;
}
public void setVar3(int var3){
this.var3 = var3;
}
}
public class B{
// Use var 1 from class A as following
A a = new A();
int x = a.getVar1(); //x has the value of Var1 now
a.setVar1(2); // var1 in class A has value 2 now.
}
Use interfaces rather than directly call a method of another class.
public class A {
private InterfaceB interfaceB;
interfaceB.method1(var1, var2, var3);
}
public interface InterfaceB{
public void method1(int var1, int var2, int var3);
public void method2(int var2, int var3);
}
public class B implements InterfaceB{
#Override
public void method1(int var1, int var2, int var3){
//doSomething
method2(var2, var3);
}
#Override
public void method2(int var2, int var3){
//doSomething
}
}
You should read about encapsulation.
Passing 3 variables encapsulated in 1 object with appriopriate accessors sounds like a better option to me (at least the code looks a bit cleaner).
Also, think of creating a utility class with static methods if it makes sense of course - sometimes you do not need class member fields at all because there is no state to this class (Math class is an example) and static methods that return the result of some calculation/transformation is a better option.
On a side note I can recommend you considering "Program to an interfaces" principle. You can read the relevant section right on the top of this page.
In B class, you declare a instance of A class, variables in A class is public. when you can use variable in A class.
Here is my 2 cents...
public class Sample {
//Property of the class
private int valueA;
//method to do some operation
//that relies explicitly on a
//property of the class
public void doSomething(){
//valueA is over 9000!?
int valueA = valueA + 9000;
}
//Method that does something that does not explicitly
//rely on a property of the class
//could be called from this or another class
public int doSomeOperationWithSomething(int something){
return something++;
}
}
Another alternative would be to create a static "utility" class for your methods
public class Utils{
public static int doMagic(int var){
return var * var;
}
}
used like this,
int num = Utils.doMagic(9);
These come about when you have some code that does that one useful thing, but you just can't figure out where to put it.
More importantly, you will want to maintain proper "encapsulation" (Read about that) in your code. This means limiting access to variables by other classes and allowing access to only what is needed.
public class Website {
//No one should ever be able to
//access this variable directly
//So we set it a private
private String article;
//A reader should be able to get the aricle
public String getArticle(){
return article;
}
//The reader should never be able to set
//an aticle on the website only read it
//You can leave this part out or
//set the method to private as i did.
private void setArticle(String article){
this.article = article;
}
}
public class Reader {
//Reference to website
private Website website;
public Reader(){
...
//the user can read an article
website.getArticle();
// but this is not available to them
website.setArticle("Some text"); // results in ERROR
}
}

Getting current object properties when calling an undeclared super method from abstract class

Probably a very basic java question.
I have an abstract class, simplifying it:
public abstract class A{
private String value = "A" ; // I want it undeclared, but set it for testing purpouse
public String getValue(){
return value ;
}
}
Then I have a class extending it:
public abstract class B{
private String value = "B" ;
}
So the problem I have is, when creating an instance of B through class A, and calling getValue(), it always return "A":
A b = new B();
b.getValue(); // returns "A"
How can I get B calling super method using his own properties without having to duplicate code? A it is currently too long, and it is extended to many different class that only differs by it properties values and all of them use the same methods that the super class has.
Thanks!
Edit:
Sorry, I wasn't so specific. I have a lot of properties, and some methods to deal with those properties. Extended class change those properties, but I want to use the super methods with the extended class instanced object without having to declare them twice. I'm working with servlets context atributtes if that helps.
Config.java
public abstract class Config {
private String someValue1 ;
...
private String someValuen ;
public void export(ServletContext cxt){
cxt.setAttribute("someValue1", someValue1);
...
cxt.setAttribute("someValuen", someValuen);
}
}
SomeConfig.java
public class SomeConfig {
private String someValue1 = "something" ;
...
private String someValuen = "something else" ;
}
SomeServlet.java
ServletContext cxt = getServletContext() ;
Config config = new SomeConfig();
config.export(cxt);
To make it clear, properties all have different names. I use them from jsp as: ${someValuen}
The reason why it doesn't work is that only methods can be overriden - variable members are hidden instead (if you print value from your B class, it will be "B").
For that specific example I would use a dedicated constructor (which I have made protected to prevent client classes from accessing it):
public abstract class A {
private final String value;
public A() { //for internal / testing use only
value = "A";
}
protected A(String value) {
this.value = value;
}
public String getValue(){
return value ;
}
}
Then B can simply call the relevant constructor:
public class B extends A {
public B() {
super("B");
}
}
EDIT
Example with a ConfigHolder:
public class ConfigHolder {
String value1;
String value2;
String value3;
public ConfigHolder value1(String value1) {
this.value1 = value1;
return this;
}
//same for other variables
}
Then in class A:
public abstract class A {
private final ConfigHolder config;
public A() {
this.config = new ConfigHolder()
.value1("value1")
.value2("value2");
}
protected A(ConfigHolder config) {
this.config = config;
}
public void export(ServletContext cxt){
cxt.setAttribute("someValue1", builder.value1);
...
cxt.setAttribute("someValuen", builder.valuen);
}
}
And in B:
public class B extends A {
public B() {
super(new ConfigBuilder()
.value1("value1InB")
.value2("value2InB"));
}
}
To do this: A b = new B(); B must be a subclass of A
Besides, an abstract class can not be instantiated, ie can not create abstract class objects. The compiler will produce an error if you try to.
public abstract class A{
private String value = "A" ;
public String getValue(){
return value ;
}
}
public class B extends A{
private String value ;
public B(){
value = "B";
}
}
Now you can do B notAbstractClass = new B();
And when doing notAbstractClass.getValue(); it must return "B"
I just figured out a simple way to do it with a constructor and changing the super class properties to protected (thanks to #assylias answer):
Config.java
public abstract class Config {
protected String someValue1 ;
...
protected String someValuen ;
public void export(ServletContext cxt){
cxt.setAttribute("someValue1", someValue1);
...
cxt.setAttribute("someValuen", someValuen);
}
}
SomeConfig.java
public class SomeConfig {
public SomeConfig(){
someValue1 = "something";
...
someValuen = "something else";
}
}

Categories

Resources