How to pass, in parameter, a class and use its methods - java

As the title presumes, how do I this in Java? What im trying to do is something like this
first there is a class
public class MyFirstModel() {
//standard constructor
public MyFirstModel(){
//some lines of codes
}
//A method
public String getvalue() {
//do something then
return result;
}
}
And the second Model(class)
public class MySecondModel() {
//standard constructor
public MySecondModel(){
//some lines of codes
}
//A method
public String getvalue() {
//do something then
return result;
}
}
Having those two, sample, models i want to pass a class depending on the, action. Let's just say there are two buttons and the first button is for the model and the second is for the second model. The third class that is to be pass to:
FinalClass fclass = new FinalClass(<class here>); <-- how do i pass the class here
Here, how do I pass the class? on the FinalClass, what would be its constructor? and how do I acces the methods of the passed class?
I hope you guys get what I mean. Please help.

You don't want to have both models implement an interface?
MyModel.java:
public interface MyModel {
public String getValue();
}
MyFirstModel.java:
public class MyFirstModel implements MyModel {
public String getValue() {
// stuff
}
}
MySecondModel.java:
public class MySecondModel implements MyModel {
public String getValue() {
// stuff
}
}
CallingClass.java:
public class CallingClass {
private MyModel model = null;
public CallingClass(MyModel model) {
this.model = model;
}
}
Then you can construct MyModel however you want and pass it in to CallingClass.

You can create an Anonymous Object by using an interface:
public interface FinalClass {
// Method definitions
}
public class MyFirstModel() implements FinalClass {
//...
}
public class MySecondModel() implements FinalClass {
//...
}
Use:
FinalClass fclass = new MyFirstModel();
// or
FinalClass fclass = new MySecondModel();

Related

Generically providing a setter for a Decorated object that is stored in an array

I'm probably going about this in the most complicated way, but I'm hoping what I'm trying to do makes sense here.
Suppose I have some set of unrelated, generated classes and I want to Decorate them to create some kind of common API. So something like:
public abstract class GeneratedDecorator<T> {
private T generated;
public T getGenerated() { return generated; }
public void setGenerated(T generated) { this.generated = generated; }
public abstract String getString();
public static class ClassA extends GeneratedDecorator<GeneratedClassA> {
#Override
public String getString() { return getGenerated().getThisString(); }
}
public static class ClassB extends GeneratedDecorator<GeneratedClassB> {
#Override
public String getString() { return getGenerated().getADifferentString(); }
}
}
Now, to use this new fancy class I just say:
GeneratedDecorator.ClassA a = new GeneratedDecorator.ClassA();
a.setGenerated(myGeneratedInstanceA);
a.getString();
Ok so far so-so ... but now I want to manage an array of these Decorators.
So let's try:
public abstract class DecoratorBundle<T extends GeneratedDecorator> {
private static final int MAX_ROWS = 10;
private T[] bundle;
DecoratorBundle() { bundle = createBundle(); }
public String getString(int index) { return bundle[index].getString(); }
public void setRow(??? generated, int index ) {
//check index of bundle, if null create a new instance of appropriate type and set bundle[index] = new instance
//call setGenerated on instance at index
}
protected abstract T[] createBundle();
public static class ClassA extends DecoratorBundle<GeneratedDecorator.ClassA> {
#Override
protected GeneratedDecorator.ClassA[] createBundle() {
return new GeneratedDecorator.ClassA[MAX_ROWS];
}
}
public static class ClassB extends DecoratorBundle<GeneratedDecorator.ClassB> {
#Override
protected GeneratedDecorator.ClassB[] createBundle() {
return new GeneratedDecorator.ClassB[MAX_ROWS];
}
}
}
Here's where I'm stuck ... I want this DecoratorBundle to have a setRow(??? generated, int index) where the parameter is of the GeneratedDecorator's type (i.e, GeneratedClassA or GeneratedClassB). Seems like type erasure will probably make this impossible, but it would be really nice to have this DecoratorBundle class to completely manage it's bundle array. It currently is able to instantiate the array, but I want some way for it to create a new GeneratedDecorator-type and assign it in a setRow method.
If I'm going about this completely wrong then I would love to hear another idea.

Refactoring java classes where methods have different parameter types

I have two classes that extend an abstract class in a very similar manner, and I'd like to abstract out the common parts since I will likely have to use this again. They each return a ThingLink containing data linking them to a Parent object. They also return a Widget that varies based on the class, but only up to their name. Here is the pattern:
public abstract class SomeClass extends TopClass {
protected abstract Widget createWidget();
public void someMethod() { // Does something }
}
public class ThingA extends SomeClass {
private static final String INFO_TYPE = "int";
public ThingLink newLink(Parent master, Int info) {
ThingLink link = new ThingLink(parent, ThingA.class);
link.addData(INFO_TYPE, info);
return link;
}
public Widget createWidget() {
// Stuff to get someData
return ThingAWidget.createMe(someData);
}
}
public class ThingB extends SomeClass {
private static final String INFO_TYPE = "String";
public ThingLink newLink(Parent master, String info) {
ThingLink link = new ThingLink(parent, ThingB.class);
link.addData(INFO_TYPE, info);
return link;
}
public Widget createWidget() {
// Stuff to get someData
return ThingBWidget.createMe(someData);
}
}
I have no access to TopClass, the ThingLink class, or the Widget class. I was trying to abstract out the common parts using generics, but I can't seem to figure out if that will provide a complete solution. My big problem is figuring out how to get the pieces that are self-referential. I would like a class something like:
public abstract class Thing<T> extends SomeClass {
private String infoType;
public void setInfoType(String type) { infoType = type; }
public ThingLink newLink(Parent master, T info {
ThingLink link = new ThingLink(parent, ???????????);
link.addData(infoType, info);
return link;
}
public Widget createWidget() {
// Stuff to get someData
return ??????????????.createMe(someData);
}
}
Keep in mind that I am fairly new to Java, and self-taught, but I am trying very hard to make some bigger leaps and really understand how to write good code. I appreciate your help.

Is there any generic way to call method of child class but the parameter is child of another type?

For example, I have 3 child classes:
public interface IPrinter{
}
public class StringPrinter implements IPrinter{
public String getInfo(String input){
return "String value:"+input;
}
}
public class IntegerPrinter implements IPrinter{
public String getInfo(Integer input){
return "Integer value:"+input.intValue();
}
}
public class BooleanPrinter implements IPrinter{
public String getInfo(Boolean input){
return "Boolean input:"+input.booleanValue();
}
}
which they are child of IPrinter, and the parameters are child of Object.
In my business code, the call of the object must be placed between some other long code (eg:loops or if-else),to get different values by different types, each time I have to copy and paste codes outside,eg:
for(a){
if(b){
result=new StringPrinter().getInfo("abc");
}
}
for(a){
if(b){
result=new IntegerPrinter().getInfo(new Integer(123));
}
}
for(a){
if(b){
result=new BooleanPrinter().getInfo(new Boolean(true));
}
}
now I want a magic function which can determine which to call automatically, eg:
public static void main(String[] args){
result=magicGetInfo<StringPrinter,String>(new StringPrinter(),"abc");
}
public static String magicGetInfo(IPrinter p,Object o){
for(a){
if(b){
//magic code, may be using template
}
}
}
is there any way to do this? I tried:
public class StringPrinter implements IPrinter{
public String getInfo(String input){
return "String value:"+input;
}
}
public interface IPrinter {
<Input extends Object> String getInfo(Input input);
}
public static <P extends IPrinter,I extends Object> String getInfo(P p,I i,Class<? extends P> c){
try{
return ((IPrinter)c.newInstance()).getInfo(i);
}catch (Exception e){
}
}
but StringPrinter cannot compile:
class 'StringPrinter' must either be declared abstract or implement abstract method

Generic Builder in Java

I created a builder for a lookup table and using it as shown below.
public class RaceCodeDataBuilder {
private RaceCode raceCode;
public RaceCodeDataBuilder() {
raceCode = new RaceCode();
}
public RaceCodeDataBuilder code(String code) {
raceCode.setCode(code);
return this;
}
public RaceCodeDataBuilder displayName(String displayName) {
raceCode.setDisplayName(displayName);
return this;
}
public RaceCode build() {
return raceCode;
}
}
Using this builder in a test:
RaceCode mockRaceCode = new RaceCodeDataBuilder()
.code("2054-5")
.displayName("Black or African American")
.build();
I am expecting lot more similar builders for other look up tables such as StateCodeBuilder, GenderCodeBuilder and all of them have just "code" and "displayName", similar to above builder.
I want to create a generic builder and avoid creating several builder classes doing the same job with different name.
I attempted something in generics but I am way off..
public class CodeDataBuilder<T>{
private T t;
public CodeDataBuilder(T t) {
this.t = t;
}
public CodeDataBuilder code(String code) {
raceCode.setCode(code); // Cant write T.setCode here for obvious resons
return this;
}
public CodeDataBuilder displayName(String displayName) {
raceCode.setDisplayName(displayName); // Cant write T.setDisplayNamehere for obvious resons
return this;
}
public T build() {
return t;
}
}
Can someone help me with that?
Thank you.
Create an interface BuildableCodeData with the methods you need, and implement it with classes like RaceData.
Your code will then look like:
public interface BuildableCodeData {
public void setCode(String code);
public void setDisplayName(String name);
}
public class Builder<T extends BuildableCodeData> {
private T codeData;
public Builder(T codeData) {
this.codeData = codeData;
}
public Builder<T> setCode(String code) {
codeData.setCode(code);
return this;
}
public Builder<T> setDisplayName(String displayName) {
codeData.setDisplayName(displayName);
return this;
}
public T build() {
return codeData;
}
}
It looks more like you should use an interface, and just make your build method return that interface. For example:
public interface Buildable{
void setDisplayName(String name);
void setCode(String code);
}
public class CodeDataBuilder {
private Buildable mObj;
public CodeDataBuilder(Buildable mObj) {
this.mObj = mObj;
}
public CodeDataBuilder code(String code) {
mObj.setCode(code); // Cant write T.setCode here for obvious resons
return this;
}
public CodeDataBuilder displayName(String displayName) {
mObj.setDisplayName(displayName); // Cant write T.setDisplayNamehere for obvious resons
return this;
}
public Buildable build() {
return mObj;
}
}
}
Then just make any object you want to build implement the Buildable interface.
If you create an interface with the needed methods:
interface CodeModel {
public void setCode(String s);
public void setDisplayName(String s);
}
You can then ask your generic class to accept only T extends CodeModel, like so:
class CodeDataBuilder<T extends CodeModel> {
// T has setCode method now!
}
Hope this helps!
If you have an interface with some standard functions, you can create a generic builder for it. The base builder would be abstract, and for each concrete implementation, there would be a concrete builder.
Interface:
public interface CodeNameable {
String getCode();
String getName();
}
Concrete implementation:
public class CodeNamedCar implements CodeNameable {
private String code;
private String name;
public CodeNamedCar(String code, String name) {
this.code = code;
this.name = name;
}
}
Abstract builder:
public abstract class CodeNameBuilder<C extends CodeNameable> {
public String code;
public String name;
public CodeNameBuilder() {
}
}
Concrete builder:
public abstract class CarBuilder extends CodeNameBuilder<CodeNamedCar> {
public CarBuilder() {
}
public CarBuilder code(String co_de) {
this.code = code;
return this;
}
public CarBuilder name(String name) {
this.name = name;
return this;
}
public CodeNameCar build() {
return (new CodeNameCar(code, name));
}
}
Then you can use it as you hoped:
CodeNamedCar car = new CarBuilder().code("thecode").name("Mazda").build();
Using this design, you'll need to check each field for correctness (non-null and non-empty, for example) in the CodeNameCar constructor. There are other ways to design it, too.
The builder pattern is about to crate a new instance of class and initialize it as much as required to do.
In the way you are going you tend to finish with a partial setter of some properties and create a possible fake relation because two object has the same attributes.
To support this in example everything has an name attribute but you do not create a super interface to called Nameable and implements its in every possible place.
If those attribute are shared across your classes you should think to create a class for them.
class Code {
int number;
String name;
}
class Race {
Code code;
//other attributes;
}
Then you have a one builder for code and another for race.
Note also that the good design is a balance of trade offs. If two fields are common for 5 classes is the a purpose to make the code complex and create a dedicated mechanize that will only pack the initialization and will not do anything productive.

Good way to implement a child class

So I have about 10-15 classes (this could grow to a much larger number in time) and they all have fairly similar variables within them:
temp
conditions
humidity
load
..And stuff like that. I'm looking to implement a parent class (abstract) to better manage this since they are all runnable.
There's a part where I call a constructor for each of them and it's... just bad.
public ThreadHandler(NH.NHandler NSH, int threadNum){
this.threadNum=threadNum;
this.NSH = NSH;
}
public ThreadHandler(OPA.OpaHandler SgeSH, int threadNum){
this.threadNum=threadNum;
this.OpaSH = OpaSH;
}
public ThreadHandler(SGE.SgeHandler SgeSH, int threadNum){
this.threadNum=threadNum;
this.SgeSH = SgeSH;
}
..... and on for 15
How would I implement a parent class to simply do
public ThreadHandler(objectType name, int threadNum){
//Do stuff
}
Thanks for any help.
You need to create an interface, say, IHandler with common methods and all handlers should implement this interface
public interface IHandler {
.... declare public methods
}
public NHandler implements IHandler {
.... implement all the methods declared in IHandler..
}
Now you can just have the following in ThreadHandler
public ThreadHandler(IHandler handler, int threadNum){
.... call the methods
}
I have another example using abstract class and extends that to ChildClass. I hope will help your problem.
ParentHandler.java
public abstract ParentHandler<T> {
public T obj;
public int threadNum;
// Declare the common variable here...
public ParentHandler(T obj, int threadNum) {
this.threadNum = threadNum;
this.obj = obj;
}
}
ChildHandler.java
public class ChildHandler extends ParentHandler<NH.NHandler> {
public ChildHandler(NH.NHandler nsh, int threadNum) {
super(nsh, threadNum);
}
}
Implement an interface, every "child" class will implement it, then you can declare an object of the interface type and create a method that returns the especific class based on something, like this.
public Interface ITest
{
string temp;
void Test(string param1, string param2);
}
public Class Class1 : ITest
{
void Test(string param1, string param2)
{
// DO STUFF
}
}
public Class Class2 : ITest
{
void Test(string param1, string param2)
{
// DO STUFF
}
}
And then:
public ITest GetClass(string type)
{
switch (type)
{
case "class1":
return new Class1();
case "class2":
return new Class2();
}
}
And you call it like
ITest obj = GetClass("class1");
obj.Test();

Categories