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");
I have a PDF file and I have a text file that contains this data. It has the name of a PDF field along with a database table column name.
Text file: pdfFieldEmployee=Employee; pdfFieldStartDate=StartDate; pdfFieldSalary=Salary; pdfFieldExempt=Exempt
I also have this hash map that contains the database table column names along with their corresponding values:
Employee, Don Parker StartDate, 5/6/2000 Salary, $55000 Exempt, N
How would I read through the text file and the hash map and at the same time do this:
if the pdf field is equal to pdfFieldEmployee, then set pdfFieldEmployee equal to Don Parker. if the pdf field is equal to pdfFieldStartDate, then set pdfFieldStartDate equal to 5/6/2000.
and so on and so on. I would prefer to do this with a loop because I think it would take less code than writing a bunch of if statements.
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:
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?
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
I was giving a quick skim to some tutorials on the internet where I have found the exception that is handled is also declared in the throws clause of the method wrapping the try-catch block. For a code representation consider the following:
public void methodName() throws IOException { try { ... } catch (IOException ex) { .... TODO handle exception }
Right, so I got this program. It takes input from the user and assigns it to fields on an object. But, it's meant to check the users input. If the user enters bad input, it's supposed to throw this exception. For each of these exceptions, theres a class specifically for it.
public class PayrollDemo { public static void main(String[] args) { Payroll pr = new Payroll ("Test Name", 234); System.out.println("Current Employee Information. "); System.out.println("Name: " + pr.getName()); System.out.println("ID: " + pr.getID()); System.out.println("Hourly Pay Rate: " + pr.getHourlyPayRate());
[Code] ....
And this is the exception class.
public class InvalidNameException extends Exception { /** No-arg constructor */ public InvalidNameException() { super("Invalid name"); } }
PayrollDemo.java:43: error: cannot find symbol InvalidNameException.InvalidNameException(); ^ symbol: method InvalidNameException() location: class InvalidNameException 1 error
It's just meant to tell the user that they entered an invalid value, which would mean if they entered an empty string instead of a name.
I've come across a piece of code and I am totally baffled by how a certain field is being incremented.
public class Foo{ private static int counter; private final int id = counter++; public int id(){return id;}
[Code] ....
Now. The output for this is: 0 1 2 3 4
I understand all the code in it quite well. It's all basic. Containers, generics, looping, foreach loop. What I DON'T understand though is how on each iteration of the foreach loop, the call to the method id() returns an incremented number. I am assuming it has something to do with the field "counter" in class Foo being static because when I made it non-static it didn't increment. I must have missed something way back when I started learning Java because I just don't get it.
The id() method only returns the value of the id field in class Foo and that is the value of counter++. counter is not initialized, though I'm guessing it gets the default 0 when the Foo() constructor is run? Or do statics get initialized BEFORE the constructor is even run? Anyway. How does calling the id() method cause an incrementation? I'd understand if there was some code that tracked the number of Foo objects being created and incrementing for each one, but I cannot see how each time the id() method is called it returns an incremented value.
I have a jsf page.i need to confirm one filed only contain double value.how to validate this? I checked and found there is a validateDoubleRange,but its not suitable for this.
i need to develop a java program in which it will ask the user "Username" and "Password" and by which it will login to a wesite.
I have developed a GUI in which the username should be entered in the User "JTextfield" and Password in Password "JPasswordField". I need to make sure that password should not be displayed in the GUI. but I didnt find a way to parse the string (char) entered in the "JPasswordField" to the website.
It is always passing a 'null' character! I tried to search in internet and i found that it wont be able to pass the passwordfield characters but you will be able to check in the main function itself by comparing with another char array in the main program itself whether the password entered is correct or not.
Is there any alternate way for this?
Objective : Parse the password (which is not displayed in the GUI) to a website or some other function where it will use it
Here are two codes that I am using but I have one that just doesn't work for some reason and the other does. Encode doesn't work. I don't need the Character.isAlphabetic for encode but not sure what I can use with 'if' to set the String encodedString.
I have a question about JTextArea colors. When i set the color to blue and then write something on the JTextArea (JTextArea.append) and then set it back to black everything will be black. How can i solve that? Like in Notepad++ or Eclipse when you write keywords in a JTextArea (where you write your code) only some words change color.
This is my code:
// All the imports public class whatever extends JFrame { JTextArea a = new JTextArea(); public whatever() { super("Title"); add(a);
I need to fill up 1/10th of the board with mines but i am only able to successfully put 1! also my goal is not showing up on the game even though i put it as an up arrow.
package Homework4; import java.util.Random; import java.util.Scanner; public class HW4 { //Creates a new type to be used to create the board
we have an Arraylist<Tweet>, and this class is defined as followe: public class Tweet implements Comparable<Tweet>, Serializable. now if we implement the method comparteTo, then will it be sorted automatically? I want to sort this array by any insert.
I'm trying to figure out a good way to allow my users to have some formatting options within a text box in my application. Ultimately, they need to be able to have text that is alternating between two separate fonts, and ideally could have both italicized and bolded words as well.
I've been using Eclipse and I realized that it compiles stuff into class files for you. So, I created a new project and each class is a separate .java file, with the .class files already there, but I cannot get rid of these errors. Or, say if I wrote them all into one file and then realized it needs to be 3 separate, or that all need to be in the same src file (oops)? Here are the errors:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: random cannot be resolved or is not a field guessp1 cannot be resolved to a variable guessp1 cannot be resolved to a variable guessp2 cannot be resolved to a variable guessp2 cannot be resolved to a variable guessp3 cannot be resolved to a variable guessp3 cannot be resolved to a variable guessp1 cannot be resolved to a variable guessp2 cannot be resolved to a variable guessp3 cannot be resolved to a variable
class A { final Object b; public A(C c) { try { b = c.someMethodThatMayThrowSomeException(); } catch (SomeException e) { b = null; // This line results in compiler error: "variable b might already have been assigned" } } // take away b=null line and you get "variable b might not have been initialized" on this line }
Why? How could 'b' be assigned if the exception was thrown?
I have been playing around with a snippet I wrote to get the Label on a drive (below). It works fine for me (though I will take any constructive criticism). My question is whether the is a way to set the drive label, purely with Java. I know I could call command line, or even resort to using the Windows API
I tried using this since the jSpinner's minimum value is 1.. (I want it to reset the jSpinner after updating the database):
jSpinner1.setValue(new Integer(1));
But gives me an error:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Vector.elementData(Vector.java:730) at java.util.Vector.elementAt(Vector.java:473) at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:649) at shop.jSpinner1StateChanged(shop.java:267) at shop.access$100(shop.java:22) at shop$3.stateChanged(shop.java:145) at javax.swing.JSpinner.fireStateChanged(JSpinner.java:457)
JFrame{ JPanel(That MenuBar at the top) JPanel(That panel at center with table){ JScrollPane{ JTable } } }
I want to add my custom image to that grey space right there. I guess it is a JScrollPane, because I added that orange background on JPanel that contains it. But when I add this code to my custom class of JScrollPane:
@Override public void paintComponent(Graphics g) { super.paintComponent(g); if(background == null){ background = new ImageIcon(ClassLoader.getSystemResource("tableBg.png")).getImage(); } g.drawImage(background, 0, 0, null); }
The result is the same, no changes.
Then I read some documentation. I found this method:
scrollPane.getViewport().setBackground(Color c);
It works, but it accepts only color and I want to add image. Is there any way to do that? Do I need to subclass JViewport and use paintComponent ? If yes, then how to make getViewport() method return my custom subclassed version?
This is my frame class, now I want to be able to change the name of the frame, and get the name with frame.getName() in another class. But I'm not sure how to do this, i tried making a new frame in that class but i feel it's just another frame and not the one i made, also tried something like