Reflection To Reduce Boilerplate Code

Jul 17, 2014

I have the following classes:

abstract class BaseClass {
}
(doesn't have to be abstract if not necessary, but currently there is no need for it not to be abstract)

class InheritedClassA extends BaseClass {
DataA a;
DataB b;
DataC c;

[Code] ....

Now, I want to get the elements like follows:

BaseClass b = new InheritedClassA();
DataA dataA = b.getDataA(); //returns the DataA field if it's a data member of the inherited class, otherwise null

I know I could do something like this:

abstract class BaseClass {
public DataA getDataA() {
return null;
}
public DataB getDataB() {
return null;

[Code] ...

and override getters as necessary in the inherited classes:

class InheritedClassA extends BaseClass {
DataA a;
DataB b;
DataC c;

public DataA getDataA() {
return a;

[Code] ...

But this introduces an awful lot of boilerplate code, especially in the BaseClass class. In my current plans, there could easily be over a hundred different Data classes, and I would have to write a method that simply returns null for each.

I read about the @Inject annotation and reflection. Is it possible to reduce or eliminate the boilerplate code with these tricks, possibly by putting new methods into the classes?

View Replies


ADVERTISEMENT

How To Reduce Number Of Parallel Arrays In Code

Mar 8, 2015

I'm building a text based "game" where you are communicating with this android creature called Gargoid , at a VERY primitive level . how it works is, simply the user type in a sentence which is decoded for meaning by comparing it with a built in list of words in order to figure out what the user is saying, and then reply with a a relevant response also from a list of built in words. the whole thing would look something like this,

user: what is your name
Gargoid : my name is Gargoid, nice to meet you
user: how is the weather
Gargoid: the weather is wonderful

so far I have 11 arrays which are the following

String[] for user typed in words used for comparison to find meaning ..An Array of String[] , 7 so far, to hold what I call the Gargoid dictionary for example String[] greeting={hi,hello,aloha}, words that indicates greeting int[] called frequency to determine which of the 7 arrays have the greatest "relevancy" to what is being said. and finally another String[] for responses here's the actual code, I want you guys to tell me if there's a way to reduce all this never ending number of arrays? and also is this code a good application of object oriented programming?

MainClass
public class GargoidMain {
public static void main(String[] args) {
TheKeyBoard keyboard=new TheKeyBoard();
TheTranslator translator=new TheTranslator();
TheBrain brain=new TheBrain();
translator.translate(keyboard.userSaysWhat());
brain.respond(translator.userSays());

[code]....

View Replies View Related

Reflection - Exception By Setting A Field Value

Jun 24, 2015

I didn't work a lot with Reflection and now I'm having troubles by writing a method to set a field value of an unknown type.
 
I wrote a little example program to show, where I cannot find a solution. I explain the problem in the following points:

- there is a class with 4 fields, which 2 are of type primitive int and 2 are Integer
- at line 27 is set the name of the field I want to modify
    - if is set field1 or field2 (of type int) there is no problem. In this case the 'case "int"' of the following switch is executed
    - if is set field3 or field4 (of type Integer) is executed the 'default' case of the following switch and at line 56 is thrown the cast exception that "Cannot cast java.lang.String to java.lang.Integer"
 
import java.lang.reflect.Field;
 
public class TestClass {
    public int field1 = 1;
    public int field2 = 2;
    public Integer field3 = new Integer(3);
    public Integer field4 = new Integer("4");
  
 [Code] .....

View Replies View Related

Annotation And Reflection Based Settings Saving System Library

Sep 12, 2014

I have been recently been working on a library to handle loading and saving settings in a Java application using annotations. Here is how the library is used currently:

package main;
import dhuk.settings.main.SettingsManager;
import dhuk.settings.main.SettingsTarget;
public class Main{
public final String keybinds = "keybinds.txt", settings = "settings.txt"; // Constant strings to be used as the file's paths
SettingsManager sm = SettingsManager.instance; // Singleton used to manage all of the settings files.

[Code] .....

Here is a link to my bitbucket repository: Click Here

View Replies View Related

How To Reduce Time In Java

Jul 3, 2014

I have two string representations of time in "HH:MM:SS" and I want to minus one time from the other.

For example if a = 10:20:30 and b = 00:50:20, i would get 09:30:10. What is the best way to do this?

View Replies View Related

Swing/AWT/SWT :: How To Reduce Jlabel With Selection Border Around It At Run Time

Sep 14, 2014

I am working on a project (assignment) and i want to be able to click on jlabel and the select border will show (as shown in the image attached) and i used it to resize the jlabel. I tried

@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
setPreferredSize(getSize());
}
});`

yet is not working. I tried some other code that are not working.

View Replies View Related

OO Principles - Reduce Number Of Methods In API Without Losing Any Functionality

Jun 20, 2014

A team of programmers is reviewing a proposed API for a new utility class. After some discussion, they realize that they can reduce the number of methods in the API without losing any functionality. If they implement the new design, which two OO principles will they be promoting?

A. Looser coupling

B. Tighter coupling

C. Lower cohesion

D. Higher cohesion

E. Weaker encapsulation

F. Stronger encapsulation

View Replies View Related

JRE :: Reduce Java Runtime Size When Bundled With Application

Mar 31, 2015

We are shipping in our company the JRE bundled with the client application in order to ensure the compatibility. But when upgrading from jre6 to jre8 the size increased by 50 MB!
 
Is there a reliable and secure way to reduce the footprint of the JRE? Are there "light distributions" or a list of libs/files that can be safely removed?

View Replies View Related

Read From User Input (integer) And Reduce It By Multiplying Its Non-zero Digits

Nov 15, 2014

Write a program that reads from the user an integer and reduce it by multiplying its non-zero digits. The result of the multiplication is a number which is to be reduced as the initial one. This process continues until an integer of one single digit is obtained. For example:

64734502 (6 * 4 * 7 * 3 * 4 * 5 * 2) 20160 (2 * 1 * 6) 12 (1 * 2) 2

Your program should display the number obtained in every iteration.

Sample run1
Enter an integer: 64734502
After iteration 1: 20160
After iteration 2: 12
After iteration 3: 2

Sample run2
Enter an integer: 97737999
After iteration 1: 6751269
After iteration 2: 22680
After iteration 3: 192
After iteration 4: 18
After iteration 5: 8

View Replies View Related

Web Services :: Code Implementation Generated By Axis2 Code Generator?

Aug 23, 2010

I was a bit confused of the code generated by the Axis2 Code Gen.

I have created a logIn(String username, String password) method in my service and used Axis2 Code Gen to generate the Stub.

I try to access the logIn method from my Client using the Stub like below:

TestServiceStub stub = new TestServiceStub("http://localhost:8080/axis2/services/TestService");
String test = stub.logIn("user","pass").

but instead of UserName and password as the parameters, the Stub created a Login object as the parameter for the logIn method. like the one below:

stub.logIn(Login login1);

I wanted to try the logIn method by providing a static userName and password but it seems impossible because the Stub changed the parameter for the logIn method.

how to test the logIn method.

View Replies View Related

Modify Code That Converts Binary Code To Decimal Numbers

Aug 29, 2014

The code here I have works fine if I just want to ask the user to enter four digits: //java application that asks user to input binary numbers(1 or 0) and convert them to decimal numbers import java.util.Scanner; //program uses class scanner public class binarynumber{
 
//main method that executes the java application
public static void main(String args[]){
//declares variables
 
int digit;
int base=2;
int degree;
double decimal;
int binary_zero=0;
int binary_one=1;
//create scanner for object input

[code]....

The thing is, I want the java application to input more than four digits for the user and I want it to loop it manytimes f until the user ask it to stop.

View Replies View Related

Input Color Code In HSV And Output Equivalent RGB Code

Oct 9, 2014

I need to create a Java program that takes an input a color code in HSV and outputs the equivalent RGB code and Vice versa.

Example:
If you test on the color RED in RGB:
Input: (255,0,0)
Output: (0,100%,100%)
If you test on the color RED in HSV:
Input0,100%,100%)
Output: (255,0,0)

View Replies View Related

Inner If Loop Code

Mar 23, 2015

Can i write inner if loop without { and } if it has more lines of code as below

public class TEst111 {
/**
* @param args
*/
public static void main(String[] args) {
int num=11;
// TODO Auto-generated method stub
if (num < 10)

[code]....

I tested to see outer if which does not need { and } even though it has multiple lines in that

View Replies View Related

Why Should Swing GUI Code Be Placed On EDT

Oct 3, 2014

According to what I read, "when programming in Swing, your GUI creation code should be placed on the Event Dispatch Thread (EDT). This will prevent potential race conditions that could lead to deadlock." (See below for code.)

Why is this? How could making a GUI lead to deadlock?

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

View Replies View Related

Code To Go From One Web Page To Next

Apr 24, 2014

I have a assignment in which the code has to scrape a web page for a little bit of data including the link to the next page, follow the link, and do this 100 times. It is scraping all the data correctly, including the link, but it isn't following the link to scrape the data on that next page. Instead, it is displaying the first page's data 100 times. I have the code in a while loop where it reads in one character at a time from the page into a string and then uses pattern matching to get the data and the next link from the string. Then it correctly displays the data and should loop back to connect to that next link and read one character at a time into the string and so on.

I have printed the link to the console and it is good. I don't get any errors. I just can't figure out where exactly the problem is. Here is my code:

import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.regex.*;
import javax.swing.* ;
public class SimpleWebSourceGetter{
static void getSourceCode(String url) {
String mystring = "";

[Code] ....

View Replies View Related

Put Some Of Code Into Methods

Apr 14, 2015

I have had to create a text analyser. I have created the program but it is all within the main method. The specification states that I have to have at least two methods within my Program.

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Analyser {
public static void main(String[] args) throws FileNotFoundException,
UnsupportedEncodingException {

[code]....

View Replies View Related

Code For Mandelbrot Set

Mar 4, 2010

i have made a code for my mandelbrot set, however, it doesn't become mandelbrot, but only an oval in the middle

import java.awt.*;
import java.lang.Object.*;
public class MandelbrotCanvas1 extends Canvas{

boolean draw = false;
ComplexNumber[][] cnSet = new ComplexNumber[600][600];
int depth = 255;
double lx = -1.5;
double ly = -1.25;
double ux = 0.5;
double uy = 1.25;
int size = 600;

[code]....

View Replies View Related

Swing/AWT/SWT :: Why Should GUI Code Be Placed On EDT

Oct 3, 2014

According to what I read, “when programming in Swing, your GUI creation code should be placed on the Event Dispatch Thread (EDT). This will prevent potential race conditions that could lead to deadlock.” (See below for code.)

Why is this? How could making a GUI lead to deadlock?

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

View Replies View Related

How To Use Coordinate In Second Code

Apr 16, 2014

how I can use this class:

Java Code:

public class Coordinate{
public int x;
public int y;
publ Coordinate(int x, int y){
this.x = x;
this.y = y;

[code]....

How would I use Coordinate in the second code?

View Replies View Related

Code Keeps Producing NaN

Mar 18, 2015

Code isn't giving me the output that I want and keeps giving me NaN

What I want -

Enter the A value for the line: 2.45
Enter the B value for the line: 4
Enter the C value for the line: -8
Enter the x coordinate of the point: 2.17
Enter the y coordinate of the point: -4

Distance from the point to the line is: 3.9831092774319026

What I am getting

Distance from the point to the line is: NaN

Here is my code-

Tester-

import java.io.*;
import java.util.*;
 class tester
{
public static double A;
public static double B;
public static double C;
public static double distance;
public static void main(String args[])

[Code] ....

View Replies View Related

Fibonacci Code In Java

Nov 30, 2014

how do we get the following numbers (1 2 3 5 8 13 21 34 55 89) out of the following code? I can't get my head around this loop....

HTML Code:

public class Fabnoci{
public static void main(String[] args)
{
int n=10,i,f0=1,f1=1,f2=1;
for(i=1;i<=n;i++)
{
f2=f0+f1;

[code]....

View Replies View Related

Write A Code Using The Stacks?

May 15, 2014

write a code using the stacks?i want the output to produce my name.

View Replies View Related

Swing/AWT/SWT :: How To Get Code Into GUI Form

Feb 12, 2014

How do I get my GUI code into a GUI format? I wrote this put it will not make a GUI image.

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Ofelia_Inventory_4;
import java.awt.*;
import java.awt.event.*;

[code]...

View Replies View Related

JSP :: Execute Code After Every 10 Seconds

Feb 25, 2014

I want to execute my jsp code to compare two dates after every 10 seconds if user enter date and current sys date are equal it will send the mail to the user automatically. Below is my jsp code

this if condition i want to check the date after every 10 seconds and when two dates are equal it will send the mail using below mail code

if(ExpcReDt.compareTo(dateStr)>0) {
out.println("Expected return date is greater than current date");
}
else if(ExpcReDt.compareTo(dateStr)==0)

[code]....

View Replies View Related

Code Only Displays Four Zeros

Jun 20, 2014

why this code only displays four zeros ?????

public class VargjetUshtrimi2 {
public static void main (String a []) {
int r[] = new int[11];
for (int i = 1 ;i < 10; i++)
{System.out.println( r[i] );}
}

View Replies View Related

Why Code Is Not Printing Matrix And Sum

Feb 28, 2014

why my code is not printing the matrix and sum?

The Java-program Matrix below first asks the user for the number of rows and columns in a matrix. After this the program asks for the values of the elements. Finally, program prints the elements of the matrix and their sum on screen. Your task is to create the missing methods. Check the example print to see how to modify the print. When printing the matrix, values on the same row are separated using tabulator.

Program to complete:

import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
int rows, columns;
Scanner reader = new Scanner(System.in);
System.out.print("Type in the number of rows: ");

[code]...

Write the missing methods here / Methods are written in the text box below.

Example output

Type in the number of rows: 3
Type in the number of columns: 4
Type in the element 1 of the row 1: 1
Type in the element 2 of the row 1: 2
Type in the element 3 of the row 1: 3
Type in the element 4 of the row 1: 4
Type in the element 1 of the row 2: 5

[code]...

Matrix:

1 2 3 4
5 6 7 8
9 10 11 12

Sum of the elements of the matrix: 78

my code

import java.util.Scanner;
public class apples {
public static void main(String[] args) {
int rows, columns;
Scanner reader = new Scanner(System.in);
System.out.print("Type in the number of rows: ");

[code]...

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved