I'm working on an Android framework (https://www.github.com/IanSwift/jumper) which takes data model classes and uses reflection to update views when they are created or updated. I use a dynamic proxy factory for this, and I currently have the user enter both the real object and an interface that specifies any state changing methods. My question is, is there a way the code could auto generate an interface from the class? It would look something like this.
Class<?> derivedInterface = somehowGetAnInterface(Original.class)
Where original is an instance something like:
public class Original {
String someData;
public void setSomeData(String s) {
someData = s;
}
public String getSomeData() {
return someData();
}
}
And derived interface gets created either at compile time or run time but looks something like this:
public interface OriginalInterface {
public void setSomeData(String s);
public String getSomeData();
}
Eclipse can do this. Select the class name, right click and select Refactor, then select Extract Interface. In the resulting dialog, provide a name for the interface and select the methods to be extracted.
BTW, when I tried this myself, I found an error in your posted code: the reference to someData in getSomeData() should be to a field, not a method.
Related
I have the following classes
class Person {
private String name;
void getName(){...}}
class Student extends Person{
String class;
void getClass(){...}
}
class Teacher extends Person{
String experience;
void getExperience(){...}
}
This is just a simplified version of my actual schema. Initially I don't know the type of person that needs to be created, so the function that handles the creation of these objects takes the general Person object as a parameter.
void calculate(Person p){...}
Now I want to access the methods of the child classes using this parent class object. I also need to access parent class methods from time to time so I CANNOT MAKE IT ABSTRACT.
I guess I simplified too much in the above example, so here goes , this is the actual structure.
class Question {
// private attributes
:
private QuestionOption option;
// getters and setters for private attributes
:
public QuestionOption getOption(){...}
}
class QuestionOption{
....
}
class ChoiceQuestionOption extends QuestionOption{
private boolean allowMultiple;
public boolean getMultiple(){...}
}
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption().getMultiple())
{...}
}
}
The if statement says "cannot find getMultiple for QuestionOption." OuestionOption has many more child classes that have different types of methods that are not common among the children (getMultiple is not common among the children)
NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.
However.. you should be able to do it like:
void calculate(Person p) {
((Student)p).method();
}
a safe way would be:
void calculate(Person p) {
if(p instanceof Student) ((Student)p).method();
}
A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:
class Person {
String name;
void getName(){...}
void calculate();
}
and then
class Student extends Person{
String class;
void getClass(){...}
#Override
void calculate() {
// do something with a Student
}
}
and
class Teacher extends Person{
String experience;
void getExperience(){...}
#Override
void calculate() {
// do something with a Teacher
}
}
By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.
In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.
Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).
I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.
http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html
The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.
UPDATE: found it here.
Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:
void caluculate(Person p){
p.dotheCalculate();
}
This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.
I had the same situation and I found a way around with a bit of engineering as follows - -
You have to have your method in parent class without any parameter and use - -
Class<? extends Person> cl = this.getClass(); // inside parent class
Now, with 'cl' you can access all child class fields with their name and initialized values by using - -
cl.getDeclaredFields(); cl.getField("myfield"); // and many more
In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.
Another thing you might need to use is Object obj = cl.newInstance();
Let me know if still you got stucked somewhere.
class Car extends Vehicle {
protected int numberOfSeats = 1;
public int getNumberOfSeats() {
return this.numberOfSeats;
}
public void printNumberOfSeats() {
// return this.numberOfSeats;
System.out.println(numberOfSeats);
}
}
//Parent class
class Vehicle {
protected String licensePlate = null;
public void setLicensePlate(String license) {
this.licensePlate = license;
System.out.println(licensePlate);
}
public static void main(String []args) {
Vehicle c = new Vehicle();
c.setLicensePlate("LASKF12341");
//Used downcasting to call the child method from the parent class.
//Downcasting = It’s the casting from a superclass to a subclass.
Vehicle d = new Car();
((Car) d).printNumberOfSeats();
}
}
One possible solution can be
class Survey{
void renderSurvey(Question q) {
/*
Depending on the type of question (choice, dropdwn or other, I have to render
the question on the UI. The class that calls this doesnt have compile time
knowledge of the type of question that is going to be rendered. Each question
type has its own rendering function. If this is for choice , I need to access
its functions using q.
*/
if(q.getOption() instanceof ChoiceQuestionOption)
{
ChoiceQuestionOption choiceQuestion = (ChoiceQuestionOption)q.getOption();
boolean result = choiceQuestion.getMultiple();
//do something with result......
}
}
}
This question already has answers here:
Implementing two interfaces with two default methods of the same signature in Java 8
(7 answers)
Closed 2 years ago.
Java 8's default methods in an interface can be called from the child class using InterfaceName.super.methodName . Why doesn't Java 8 allow us to use a similar syntax to call the specific class's method name? Can this resolve the Diamond Problem encountered for multiple inheritance?
class Employee {
public static void displayName() {
System.out.println("Employee!");
}
}
class Engineer extends Employee {
public static void displayName() {
System.out.println("Engineer!");
}
}
class Manager extends Employee {
public static void displayName() {
System.out.println("Manager!");
}
}
public class Resource extends Engineer,Manager {
public static void main(String args[]) {
//Insert similar code here like InterfaceName.super.methodName to call any of the above methods to handle multiple inheritance.
}
}
In Java 8, you can not extend (inherit) multiple classes all in one shot. What I mean by this is that if you write:
public class Resource extends Engineer, Manager { //This generates a compiler error.
}
However, you may inherit multiple classes into one, main class by making a chain of inheritance.
public class Master {
public void method1(){};
}
public class Child1 extends Master{
public void method2() {};
}
public class Child2 extends Child1 {
//you can access method 1 and method 2 here by simply calling
method1();
method2();
}
A way you can go about addressing your issue is to write an "EmployeeInterface" and write an "EmployeeClass". To access the methods in "EmployeeClass", you must make an object of the "EmployeeClass" in your main method. You will need to write a constructor to pass the name of the employee in. I will provide an example here:
public interface EmployeeInterface {
public void displayName();
public void setName(String name);
}
The above is an Interface. An interface contains the methods that you want to use in a class, however, you do not yet define them here. You only write the method headers. Think of this as a shopping list. Writing an item such as bread on a shopping list does not mean you will now have bread, it just marks it as an item that needs to be purchased.
Next, you will need to write a class implementing the EmployeeInterface.
public class EmployeeClass implements EmployeeInterface{
private String employeeName;
public EmployeeClass(String name) { //This is a constructor
this.employeeName = name;
}
#Override
/**
* This function will display the name of the employee.
*/
public void displayName() {
System.out.println(employeeName);
}
#Override
/**
* This function with use the given string and change the employee's name.
*/
public void setName(String name) {
this.employeeName = name;
}//end of setName method
}//end of class
Above is the class that implements the EmployeeInterface. It looks at the Interface and says that you must define what these methods do. This is like looking at your shopping list and seeing bread, and going to the store and buying it.
There is also a constructor in this class. A constructor in java is a method that is executed upon the instantiation of an instance of a class. This means that whatever code you write in the constructor, it will be run once and only once when you make an object of the class. Constructors must be spelled the same as the class, is case sensitive, and must be public. You can add as many parameters as you'd like.
We use #Override over the functions in the class because we are overriding (Changing the body) from nothing to our definition from the EmployeeInterface. Depending on your IDE/Compiler, it may work without the #Override tag, but it is highly reccomended that you do this.
In the constructor, you see we use this.employeeName = name; the "this" keyword refers to the field (variable) within the class that we write it in. In this case, it is not necessary, because the name of the variable in the class and the name of the variable being passed in are different. But in the case that variable names are the same, you can use "this.variableName" to specify the class variable.
Finally, to use these classes, you must make a main method in a separate class to execute these functions. Making the main method is like making a sandwich out of the bread that you purchased at the store.
public class Main {
public static void main(String[] args) {
EmployeeInterface manager = new EmployeeClass("Bob");
EmployeeInterface engineer = new EmployeeClass("Mary");
System.out.println("The name of the manager is: ");
manager.displayName();
System.out.println("The name of the engineer is: ");
engineer.displayName();
manager.setName("Jack");
System.out.println("The new manager's name is: ");
manager.displayName();
}//end of method Main
}//end of class Main
Above is the method that executes the methods that you defined in the EmployeeClass using the EmployeeInterface. First, you create an object of the class, of the type that is the name of the Interface.
EmployeeInterface manager = new EmployeeClass("Bob");
This is an object of the EmployeeClass, and we called it manager. We made it of type EmployeeInterface because we want to be able to use the methods we defined in the EmployeeInterface. We write "= new EmployeeClass("Bob");" afterward because we want to make a new Instance of the EmployeeClass, and pass the String "Bob" into our constructor.
Next, we display the name of the manager.
System.out.println("The name of the manager is: ");
manager.displayName();
This will display the name of the manager.
We can also change the name of the manager with our defined "setName()" function.
manager.setName("Jack");
We call the function like this and pass in the String "Jack" which will become the new name for the manager.
Upon execution of the Main method, we get this output:
Image of the output
All in all, this solution does not use inheritance of methods to print the names of different employees, but uses an EmployeeInterface, along with a definition of the Interface, EmployeeClass, to store and display the employee names. Rather than making a new class for every employee, you make a new object with the parameters containing the name of the new employee in the main method.
I hope this answered your question, and please do reply if you require any more clarifications.
Here I also include some articles about the Java concepts I talked about.
Here is a resource for Inheritance and Interfaces.
Interfaces on Oracle
Inheritance on Oracle
Constructors on Oracle
My task is to create stubs for a 3rd party Java library that our application will make calls to. My problem is how to define the class of the method "return type" (if that's the correct Java terminology). I don't have access to the full documentation of the 3rd party API, just a list of methods. For now, my stubs just need to return true/false or 1/0, whatever
Here's an example of one method to illustrate. This is what I have been given
OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode)
I have no idea what OobResponse or RequestMode are supposed to be, but I should still be able to create stubs, right?
So far, this is all I have.
public class stubber {
public class OobResponse {
public int someVar;
}
public class RequestMode {
public int someVar;
}
public OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode)
{
OobResponse oobr = new OobResponse();
return oobr;
}
}
The documentation you have is weird, since variable and method names do not hold Java convention of using camelCase. Also, what you seem to be ordered to do would hold minimal later use. However, the way I understand your problem you could do:
create new package for all classes you will be stubbing. That will be relevant later
actually stub stuff. That is, for every class in the documentation that is not built into java create the class. I assumed that what you wrote is a method declaration (made most sense to me, though it could also be a constructor or whatever), it needs to be a part of some class, I called it "Unknown" below. Replace that name with actual class name.
For your example you would need:
public class RequestMode {
}
public class OobResponse {
}
public class Unknown {
public OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode){
return new OobResponse(); // or null, whatever since it is a stub
}
}
Note, that when stubbing you do not create any additional variables (like someVar you tried to add), ONLY what API allows you to access (only classes and public methods within would be a good rule of a thumb). You could also use interfaces instead of classes, it would be cleaner, but there are legitimate reasons not to (when you want a code with new StubbedClass() to compile for example).
Now, in your actual code you (or someone) will be able to use your stubs like the actual library:
public class YourBusinessClass{
public OobResponse getOobByClientName(String clientName){
return new Unknown().RequestOobRequest(clientName,...);
}
}
When you get the actual library you can replace imports from stub package in your actual code that uses it to the actual library package.
That is the only usefull way of using stubs like that I could think of, so I hope that is what you want.
One possibility (academically at least) is to use a facade to the actual 3rd party library. You could probably create a class which has the methods that you need and your main code calls this class in place of the the 3rd party library, include all the methods that you need and return 1/0 etc., when the library is available dispatch the calls to the library from the facade.
However, there is a fair bit of caution, if the actual data model of the library is complex you could end up replicating all of them or their equivalent in your code, if it is not (like simple strings etc.) then this approach would work.
With reference to the comment below for en example, i am adding the following:
Let us say we have a class:
public class Class0{
public String method0(String arg0){return "from Method 0";}
public String method1(String arg0, String arg1){return "from Method 1";}
}//class closing
Now let us say we only have the signature for the above class and not the class itself, then we can do the following (for now):
public Class0Facade{
public String method0(String arg0){return "from Method 0";}
public String method1(String arg0, String arg1){return "from Method 1";}
}//class closing
Rest of your code can use the 'class0Facade' class and go ahead.
When the actual Class0 is available, you would change Class0Facade, in the following way:
public Class0Facade{
protected Class0 deligate;
public Class0Facade(){delegate=new Class0();}
public String method0(String arg0){return delegate.method0(arg0);}
public String method1(String arg0, String arg1){return delegate.method(arg0, arg1);}
}//class closing
Rest ot four code does not need to change
Maybe you could go with classes that extend the stubbed classes:
public class Stubber extends StubbedClass {
public OobResponse RequestOobRequest(
String ClientName,
String SecurityLink,
short LenofHHU,
RequestMode RequestMode) {
OobResponse oobr = new OobResponse();
return oobr;
}
}
If you cant create an OobResponse, you could similarly create a public class OobResponseStub extends OobResponse
In my scenario I have a BaseObject which is an interface and then a BaseObjectImpl.
Then I have two clients, ClientA and ClientB which both reference BaseObjectImpl with the minor different being that the constructor argument to BaseObjectImpl should change depending on which client is using it. The setup looks like this:
BaseObject:
public interface BaseObject {
void doAction();
}
BaseObjectImpl:
public class BaseObjectImpl implements BaseObject {
#Inject
public BaseObjectImpl(RandomInjectedObject random, String inputString) {
this.inputString = inputString;
}
public void doAction() {
// print input string
}
Now for the clients:
ClientA:
public class ClientA {
#Inject
public ClientA(BaseObject baseObject) {
this.baseObject = baseObject;
}
ClientB:
public class ClientB {
#Inject
public ClientB(BaseObject baseObject) {
this.baseObject = baseObject;
}
Now the issue is that when inside my ClientAModule I want to provide the inputString argument such that it is set to clientAString and inside ClientBModule I want to provide clientBString instead.
What is the best way to go about doing this? Note that the BaseObjectImpl takes in two arguments (the other one has the same definition for both clients).
What I tried doing was inside the BaseObjectModule class that I have defined, I created a Builder inside which I could set a specific annotation and set a specific inputString. Then inside my Client<AB>Module I created a different BindingAnnotation in each of them. Then when I installed the BaseObjectModule I did so using the builder and each passed in their specific BindingAnnotation and inputString.
Then I try to bind the BindingAnnotation / inputString scope to a Provider for BaseObject is that I try to instantiate the BaseObjectImpl with the corresponding inputString and the injected RandomInjectedObject which I've provided also in the BaseObjectModule. I get an error saying:
This Provider cannot be used until the Injector has been created because I haven't created the injector inside the module itself.
I was looking at AssistedInjection so that I could make it so I just passed in the inputString at this time, but the problem is I still need the injector for that.
I am using Eclipse IDE for my Java project. I need a list of methods which are being called from a particular class i.e. I need to see a list of all the methods which are being called from a class but not declared in that. I am looking for some option which might be there in Eclipse already. I am not willing to write a code for this (that will be my last choice).
Let me explain using this example -
public class ABC {
public void methodA {
System.out.println("In methodA");
BCD bcd = new BCD();
bcd.callMethodAA(); // defined in class BCD
}
public void methodB {
System.out.println("In methodB");
CDE cde = new CDE();
cde.callMethodBB(); // defined in class CDE
}
}
I want an option which will show me -
From Class ABC we are calling -
a) callMethodAA
b) callMethodBB
If you need to list only the method being used, there is no in-language way to achieve that. Though there might be some coverage tools which can handle this.
But If its about all the available methods, you can use reflection:
Class<?> cls = Class.forName("className");
Method[] methodList = cls.getMethods();
To find the methods that are called from a class (assuming programatically), I would use the ASM bytecode analyzing/manipulation library. The below example is a ClassVisitor that prints all the methods called from a class.
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.commons.InstructionAdapter;
public class MethodCallFinder extends ClassAdapter {
private String name;
public MethodCallFinder(ClassVisitor classVisitor) {
super(classVisitor);
}
#Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
this.name = name;
super.visit(version, access, name, signature, superName, interfaces);
}
#Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
return new MethodCallPrinter(super.visitMethod(access, name, desc, signature, exceptions));
}
private class MethodCallPrinter extends InstructionAdapter {
public MethodCallPrinter(MethodVisitor methodVisitor) {
super(methodVisitor);
}
#Override
public void visitMethodInsn(int opcode, String owner, String name, String desc) {
System.out.printf("Class %s calls method %s with descriptor %s from class %s%n", MethodCallFinder.this.name, name, desc, owner);
super.visitMethodInsn(opcode, owner, name, desc);
}
}
}
You can do it by creating a single method that invokes all the methods on your class. If you already have one of those even better. Take the Logo.java class from Junit as an example if I create this:
private void ExposeAllCalledMethods()
{
Logo x = new Logo();
x.loadImage("something");
Graphics g;
x.paint(g);
}
Note I didn't need to call paintBackround() because paint() already calls it.
Then I can right-click in the method name ExposeAllCalledMethods and select Open Call Hierarchy. Then in the call hierarchy window click on the Callees button (see the green arrow in the image) and open all the gray hierarchy arrows as shown in the image below. A complete list of all methods called by the current class is shown.
<Shameless Plug> Now I wish I had shown how to do this in my new Pluralsight Eclipse course. </Shameless Plug>
.
In Eclipse, you can do this by selecting (highlighting) the method in an editor pane, then constructing the Call Hierarchy (probably Ctrl-Alt-h). You can then switch from "Show Caller Hierarchy" (default) to "Show Callee Hierarchy" using the toggle buttons in the top-right of the Call Hierarchy pane. The one you want looks like sideways tree with children to the right, like o-[ not ]-o.
str + o
lists all methods available in the class that is currently open.
does this answer your question?
If it is at runtime, you could use a Dynamic Proxy.
The dynamic proxy is called before the method invocations of your class and you can log somewhere (to another class, or a file or whatever) which methods have been called.
The answer dependents on the context:
If you like to have this for your code within your IDE: This depends on the IDE. In Eclipse, I believe, it is not possible. You can get the method which calls a given class (constructor of method) via "Open Call Hierarchy".
If you like to do it at runtime: This is solvable with AspectJ, see for example http://www.eclipse.org/aspectj/doc/released/progguide/language-thisJoinPoint.html (at the end there is a piece to get the caller of any method).