Is there a way to find out which class instance created 'this' - public

**I(one instance of a class) want to find out say which class instantiated me?
I have a class C that is instantiated by Class A and Class B. I want to find out which class instantiated me, so that I can access the variable from that class.
The usual way is to pass in an identifier that hey I am from class A and pass in the variable x in the constructor for the C to consume in the way appropriate for it.
**
eg:
public Class A
{
public int x;
public A()
{
C c = new C();
}
}
public Class B
{
public int x;
public B()
{
C c = new C();
}
}
public Class C
{
public CMethod()
{
// I want Access int x from the class that instantiated me.
if I know its B then B.x ...
}
}

There is no way to know without some hacking (see below). This looks like a case for an interface…
Classes A and B define HasX which has a getX() method. You can pass either class to the constructor of C which expects any class which implements HasX. Then C can call getX on either object and it doesn't need to know which type it actually is, but it will get the appropriate X value.
public interface HasX {
public int getX();
}
public class A implements HasX {
private int x;
public A()
{
C c = new C(this);
}
public int getX() {
return x;
}
}
public class B implements HasX {
private int x;
public B() {
C c = new C(this);
}
public int getX() {
return x;
}
}
public class C {
HasX hasX;
public C(HasX hasX) {
this.hasX = hasX;
}
public void doStuff() {
int x = hasX.getX();
}
}
To answer you original question though, the object which created an object is not stored anywhere… but you can do some hacking when C is constructed for find out the class. Here is some code I once used for a Logging implementation which could detect who was the caller by looking back along the stracktrace of a Throwable. Again, this is not good practice, but you asked so… :)
From: https://github.com/slipperyseal/atomicobjects/blob/master/atomicobjects-lang/src/main/java/net/catchpole/trace/PrintTrace.java
public C() {
String whoCalledMe = whereAmI(new Throwable());
}
private String whereAmI(Throwable throwable) {
for (StackTraceElement ste : throwable.getStackTrace()) {
String className = ste.getClassName();
// search stack for first element not within this class
if (!className.equals(this.getClass().getName())) {
int dot = className.lastIndexOf('.');
if (dot != -1) {
className = className.substring(dot + 1);
}
return className + '.' + ste.getMethodName();
}
}
return "";
}
You might want to edit this to simply return the class name, or even do a Class.forName() to resolve the actual class.
If you want the actual objects, and there is only ever 1 of each class, you could out the objects in a Map keyed on classname. But gee what a mess around :)

Related

How to define a helper method shared by multiple classes?

what would be the best way to go about this? For instance, consider the following code:
public class ObjectA {
public int data;
public ObjectA() {
this.data = 1;
}
public changeData(int x) {
this.data = x;
}
}
public class ObjectB {
public int data;
public ObjectB() {
this.data = 1;
}
public changeData(int x) {
this.data = x;
}
}
How can this be refactored so changeData can have both classes can use it? Also, so that changeData will be safe to use.
You could create your helper function and data as part of a base class and derive all other classes from it.

Groovy bug: category does now work with abstract iterable classes

I've noticed that Groovy version 2.4.x completely breaks my DSL language. After some time, I have reduced the problem: Groovy category now does not work with abstract iterable classes.
Consider example:
// a very simple Java abstract class that implements Iterable
public abstract class MyAbstractClass implements Iterable<Number> {
public final int num;
public MyAbstractClass(int num) { this.num = num; }
#Override
public String toString() { return String.valueOf(num); }
#Override
public Iterator<Number> iterator() {
//just some dummy empty iterator
return new Iterator<Number>() {
#Override
public boolean hasNext() { return false; }
#Override
public Number next() { return null; }
};
}
}
// a single implementation
public class MyAbstractClassImpl extends MyAbstractClass {
public MyAbstractClassImpl(int a) { super(a); }
}
//category that overloads PLUS operator
class MyCategory {
public static MyAbstractClass plus(MyAbstractClass a, MyAbstractClass b) {
return new MyAbstractClassImpl(a.num + b.num);
}
}
And the test case:
use(MyCategory) {
def a = new MyAbstractClassImpl(1)
def b = new MyAbstractClassImpl(2)
println a + b //expected 3, but received []
assert (a + b).num == 3 // so here we see exception
}
So, instead of using plus defined in MyCategory, Groovy converts each argument to List and then uses plus from the default Groovy methods defined for the List.
I've created a ticket in Groovy issue tracker, but for now this bug completely breaks my DSL language and I can't force the users to use the previous version of Groovy (in 2.2.x all works fine). So, can one suggest any workaround until this bug will be fixed ? (and if it will be ever fixed...)

Accessing the value of class variable defined in a class from another class

I have the following scenario . I have three classes
CLass A
Class B
Class C
In Class A an object of Class B is created.
In Class B an object of class C is created.
There is a public class variable defined in Class C
which I want to access using an object of Class A in a page.
Is there any way to do this directly ?
Thanks in advance
Regards
Mathew
You could create a property on A that references the C object:
class A
{
public B B { get; set; }
public int CFoo { get { return B.C.Foo; } set { B.C.Foo = value; } }
public A() { B = new B(); }
}
class B
{
public C C { get; set; }
public B() { C = new C(); }
}
class C
{
public int Foo { get; set; }
}
From your page, you would do this:
A a = new A();
// sets A.B.C.Foo
a.CFoo = 1;

how interface know which class method call?

i have one doubt if if we have two classes with same method,object of class doesnt know which method to call this situtation we use interface? but how interface know which class method to call,how to apply interface ,i have some code plz check and tell me?
namespace IntExample
{
interface Iinterface
{
public void add();
public void sub();
}
public partial class Form1 : Form,Iinterface
{
public Form1()
{
InitializeComponent();
}
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
public void sub()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a - b;
txtresult.Text = c.ToString();
}
private void btnadd_Click(object sender, EventArgs e)
{
add();
}
private void button2_Click(object sender, EventArgs e)
{
sub();
}
class cl2 : Form1,Iinterface
{
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
}
}
}
An interface is an abstraction, one that allows you to perform polymorphism without the need for inheritance. As such, an "interface variable" holds an instance of a concrete class, and the current instance's class is always used for method lookups by the interface as long as the variable contains that instance.

Unable to cast object of type X to Y

I keep getting the exception “Unable to cast object of type X to Y” in some code. I’ve got an interface and two classes that implement it and it keeps throwing this error when casting from one to the other. The two classes and interface are in the same namespace in the same assembly so that’s not the issue. I created an isolated console application to figure this mess out but I can’t get them to cast to one another. I think I’ve forgotten some basic .Net rule here. Anything look off in this code to you?
My isolated app code:
class Program
{
static void Main(string[] args)
{
RecurringPaymentResult r = new RecurringPaymentResult();
r.AddError("test");
ProcessPaymentResult p = null;
p = (ProcessPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult"
p = (IPaymentResult)r; // Doesn't compile. "Cannot convert type RecurringPaymentResult to ProcessPaymentResult. An explicit conversion exists (are you missing a cast?)"
p = (ProcessPaymentResult)((IPaymentResult)r); // Compiles but throws: "Unable to cast object of type RecurringPaymentResult to ProcessPaymentResult" during runtime
}
}
My core code:
public interface IPaymentResult
{
IList<string> Errors { get; set; }
bool Success { get; }
void AddError(string error);
}
public partial class RecurringPaymentResult : IPaymentResult
{
public IList<string> Errors { get; set; }
public RecurringPaymentResult()
{
this.Errors = new List<string>();
}
public bool Success
{
get { return (this.Errors.Count == 0); }
}
public void AddError(string error)
{
this.Errors.Add(error);
}
}
public partial class ProcessPaymentResult : IPaymentResult
{
private PaymentStatus _newPaymentStatus = PaymentStatus.Pending;
public IList<string> Errors { get; set; }
public ProcessPaymentResult()
{
this.Errors = new List<string>();
}
public bool Success
{
get { return (this.Errors.Count == 0); }
}
public void AddError(string error)
{
this.Errors.Add(error);
}
// More properties and methods here…
}
One major mistake I see in your code is saying "p =".
You have already decided the type of p and you are assigning various other variables in this type which is wrong.
Below are all possible conversions available :
RecurringPaymentResult r = new RecurringPaymentResult();
r.AddError("test");
ProcessPaymentResult p = null;
var r1 = (IPaymentResult)r; //type of r1 becomes IPaymentResult
var r2 = (IPaymentResult)p; //type of r2 becomes IPaymentResult
var r3 = (RecurringPaymentResult)r1; //type of r3 becomes RecurringPaymentResult
var r4 = (ProcessPaymentResult)r2; //type of r4 becomes ProcessPaymentResult
Logical explaination:
Man (class) has Eye(interface) and Elephant(class) has Eye(interface). Interface provides See method(). Both Man and Deer implements Eye interface by having See method in them.
Now, What you are trying is converting Man object into Elephant object which is not possible as space to store those objects have different requirements.

Resources