I think I have a simple mistake in my code but I can't find it.
I have a list of Objects (type of an entity) and I want to read the content of the objects in the list.
In my opinion something like:
object.get(1).getTitle();
List<HtMeldungen> meldungen = q.getResultList();
List<MeldungsBean> meldungsliste = new ArrayList();
MeldungsBean mb = null;
HtMeldungen tempMeldungen = null;
int i = 0;
int k = meldungen.size() - 1;
for (i = 0; i < k; i++) {
mb = new MeldungsBean();
tempMeldungen = (HtMeldungen) meldungen.get(i);
mb.setTitel(tempMeldungen.getTitle());
mb.setAutor(tempMeldungen.getAutor());
mb.setMeldungstext(tempMeldungen.getText());
meldungsliste.add(mb);
}
My list named meldungen is filled with objects of type HtMeldungen.
I get the error:
DBEntities.classic.HtMeldungen cannot be cast to DBEntities.classic.HtMeldungen
Can anyone help me?
Are you sure q.getResultList() gets a list with instances of HtMeldungen?
If not, then the line
List<HtMeldungen> meldungen = q.getResultList();
is - depending of your compiler switches - syntactically correct, but the list can contain instances of a different class, and later in the line
tempMeldungen = (HtMeldungen) meldungen.get(i);
you get your exception, because that what the compiler thinks it must be instance of HtMeldungen in fact isn't.
Try the code
if (meldungen.get(i) instanceof HtMeldungen) {
tempMeldungen = (HtMeldungen) meldungen.get(i);
} else {
throw new RuntimeException("Got instance of class " + meldungen.get(i).getClass());
}
then you get an understandable error if your assumption should have been wrong.
I'll get the error: DBEntities.classic.HtMeldungen cannot be cast to DBEntities.classic.HtMeldungen
Since the error message indicates that an object of HtMeldungen cannot be cast to HtMeldungen (which seems contradictory), I would think that you might have this class loading twice in your build. Please check to see if your build path is putting the same jar in the build twice. That is what usually causes this error.
Related
In order to make my code more readable, I decided to create a String, and then to use it inside an "algorithm" (similar to the following):
JsonArray users = import();
String currentUser = db.getName(currentID);
for (int i=0; i < users.size(); i++) {
user = (JsonObject) users.get(i);
if (user.get("username").getAsString().equals(currentUser)) {
System.out.println("The user's index is " + i);
}
}
currentUser = null; // This line raises the warning
When the "algorithm" is done, I want to delete the String - and therefore I assign it null (after reading this).
However IntelliJ doesn't seem to like it, because it raises the obvious warning:
The value null assigned to 'currentUser' is never used (...)
Is there a better way to delete objects that I'm missing, or is it just a bug that I can ignore?
At work, we have to generate a report for our client that changes its parameters several times during the week.
This report is generated from a single table on our database.
For example, imagine a table that has 100 columns and I have to generate a report with only 5 columns today, but tomorrow I have to generate with 95 of them.
With this in mind, I created a TO class with all the columns of the specified table and my query returns all columns (SELECT * FROM TABLE).
What I'm trying to create is a dynamic form to generate the report.
I first thought on create a simple frame with a list of the columns listed as check boxes and the user would select the columns that he wants (of course with a button to Select All and another to Deselect All).
As all of the columns have the same name as the attributes of the TO class, I developed the following code (I have Google this):
Class c = Test.class;
for(int i = 0; i < listOfAttributes.length; i++)
{
auxText += String.valueOf( c.getMethod( "get" + listOfAttributes[i]).invoke( this, null ) );
}
Is this the better way to do what I need to?
Thanks in advance.
Obs.: the getters of the TO class have the pattern "getAttribute_Name".
Note: This question is different from the one where the user is asking HOW to invoke some method given a certain name. I know how to do that. What I'm asking is if this is the better way to solve the problem I described.
My Java is a little more limited, but I believe that's about as good as you're going to get using reflection.
Class<?> c = Test.class;
for (String attribute : listOfAttributes) {
auxText += String.valueOf(c.getMethod("get" + attribute).invoke(this, null));
}
But since this sounds like it's from potentially untrusted data, I would advise using a HashMap in this case, with each method explicitly referenced. First of all, it explicitly states what methods can be dynamically called. Second, it's more type safe, and compile-time errors are way better than runtime errors. Third, it is likely faster, since it avoids reflection altogether. Something to the effect of this:
private static final HashMap<String, Supplier<Object>> methods = new HashMap<>();
// Initialize all the methods.
static {
methods.set("Foo", Test::getFoo);
methods.set("Bar", Test::getBar);
// etc.
}
private String invokeGetter(String name) {
if (methods.containsKey(name)) {
return String.valueOf(methods.get(name).get());
} else {
throw new NoSuchMethodException();
}
}
It might sound like a major DRY violation to do so, but the repetition at least makes sure you don't wind up with unrelated getters accidentally called.
Class c = Test.class;
for(int i = 0; i < listOfAttributes.length; i++)
{
auxText += String.valueOf( c.getMethod( "get" + listOfAttributes[i]).invoke( this, null ) );
}
You can do this somewhat more elegantly via Java Beans, the Introspector, and PropertyDescriptor, but it's a little more long-winded:
Map<String, Method> methods = new HashMap<>();
Class c = this.getClass(); // surely?
for (PropertyDescriptor pd : Introspector.getBeanInfo(c).getPropertyDescriptors())
{
map.put(pd.getName(), pd.getReadMethod();
}
//
for (int i = 0; i < listOfAttributes.length; i++)
{
Method m = methods.get(listOfAttributes[i]);
if (m == null)
continue;
auxText += String.valueOf(m.invoke(this, null));
}
For some reason, when I compile this simple code, an error pops up. (If I had 10 rep I would post it) It basically says (File Directory) uses unchecked or unsafe operations. Recompile with -Xlint: unchecked for details. I experimented a little and it seems if I take away the Bin.add() the error goes away. Can someone explain what I should do?
import java.util.ArrayList;
public class Summoned_Bin
{
ArrayList Bin = new ArrayList();
Summoned_Bin()
{
}
void addToBin()
{
Summon summoned = new Summon();
int index = 0;
while (Bin.get(index) != null)
{
index++;
}
Bin.add(index , summoned ); //Without this it runs fine
}
}
I think it wants you to type the list List<Summon> Bin = new ArrayList<Summon>();
Three things to note:
Declare the type as List<Summon> instead of ArrayList<Summon> its best practice to use the interface, which will allow you to change the type at a later date.
The Summoned_Bin class should follow Java naming standards, so SummonedBin should be the name.
Also the name of the SummonedBin object should follow Java naming standards, use bin instead of Bin.
Revised Class
public class SummonedBin {
List<Summon> bin = new ArrayList<Summon>();
SummonedBin() {
}
void addToBin() {
Summon summoned = new Summon();
int index = 0;
while (bin.get(index) != null) {
index++;
}
bin.add(index, summoned);
}
}
It's not error, it's only warning.
You want to do explicit type definition:
ArrayList<Summon> Bin = new ArrayList<Summon>();
I have written this method. I want to write a Bayesian Network, but I get an exception on the classifyInstance() method.
Here is my code:
public static double bayesNet1(Dataset data, Dataset testingSet) throws Exception {
Instances insts = convertTxtToARFF(data);
K2 learner = new K2();
MultiNomialBMAEstimator estimator = new MultiNomialBMAEstimator();
estimator.setUseK2Prior(true);
EditableBayesNet bn = new EditableBayesNet(insts);
bn.initStructure();
learner.buildStructure(bn, insts);
estimator.estimateCPTs(bn);
double error = 0;
Instances instsTest = convertTxtToARFF(testingSet);
for(int i=0; i<instsTest.numInstances()-1; i++) {
weka.core.Instance inst = instsTest.instance(i);
double predictedValue = bn.classifyInstance(inst);
if(inst.value(inst.classIndex())!= predictedValue)
error++;
}
return error/instsTest.numInstances();
}
And here is the exception:
java.lang.ArrayIndexOutOfBoundsException: 4 at
weka.classifiers.bayes.net.estimate.DiscreteEstimatorBayes.getProbability(DiscreteEstimatorBayes.java:106)
at
weka.classifiers.bayes.net.estimate.SimpleEstimator.distributionForInstance(SimpleEstimator.java:183)
at
weka.classifiers.bayes.BayesNet.distributionForInstance(BayesNet.java:386)
at weka.classifiers.Classifier.classifyInstance(Classifier.java:84)
at
ensembleClassifiersV2.EnsembleClassifierV2.bayesNet1(EnsembleClassifierV2.java:1090)
at
ensembleClassifiersV2.EnsembleClassifierV2.performing(EnsembleClassifierV2.java:800)
at
ensembleClassifiersV2.EnsembleClassifierV2.main(EnsembleClassifierV2.java:1267)
Can anyone help me what is wrong?
I have the same problem. My fault is I had not set the class for the test data. As simple as that.
I find that this error commonly occurs in the distributionForInstance() method for many of the different classifiers when you are dealing with nominal attributes.
If this is the case, it could be that the test data has a nominal attribute with an attribute value that the train data lacks.
In this case, it really depends upon what the best decision is for what you are doing. Perhaps checking the data itself for consistency is the first step and then you go from there.
For some reason I am receiving errors in the code below and I can't see why, can you spot any?
public void delTask_mouseClicked(MouseEvent e)
{
if(delTask.isEnabled() == false) {
int numTasks = taskTable.getRowCount();
Object[] currentTasks;
currentTasks = new Object[numTasks];
for (int i = 0; i < numTasks ; i++){
Object tasks = taskTable.getModel().getValueAt(i, 1);
currentTasks[i] = tasks;
}
System.out.println(currentTasks);
}
}
Thanks for the help, it's really appreciated.
There massive block of errors I am getting is below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at projecttaskmanagement.ProjectGUI.delTask_mouseClicked(ProjectGUI.java:233)
at projecttaskmanagement.ProjectGUI$2.mouseClicked(ProjectGUI.java:109)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:212)
at java.awt.Component.processMouseEvent(Component.java:5520)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3901)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
CODE AT LINE 233:
int numTasks = taskTable.getRowCount();
TASK TABLE IS DEFINED BELOW:
String[] taskcolumnNames = {"ID #",
"Name",
"Description",
"Start Date",
"End Date",
"Staff",
"Completed"};
Object[][] taskdata = {
{new Integer(1), "Requirements Analysis",
"Analysing the requirements",
"01/09/2011", "15/10/2011",
"Bob", new Boolean(true)},
{new Integer(2), "System Design",
"Designing the System",
"15/09/2011", "15/10/2011",
"Alice", new Boolean(true)},
{new Integer(3), "Code (A)",
"Part 'A' of coding",
"01/10/2011", "15/11/2011",
"David", new Boolean(true)},
};
JTable taskTable = new JTable(taskdata, taskcolumnNames);
While we're waiting for you to post the actual errors you're getting (a), please take a moment to NEVER do this:
if (delTask.isEnabled() == false)
A much better form is the simpler-to-read:
if (! delTask.isEnabled())
We now return you to your scheduled programming, pending your update.
Dum de dum de dum ...
Now, based on your update, the following part of the stackdump:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at projecttaskmanagement.ProjectGUI.delTask_mouseClicked(ProjectGUI.java:233)
indicates where the problem lies. Find out which of those lines of yours in line number 233 and there you have it. The thing that you're trying to deference on that line is in fact a null reference.
Based on the snippet, it'll probably be one of the following lines:
public void delTask_mouseClicked(MouseEvent e)
{
if(delTask.isEnabled() == false) { // <--
int numTasks = taskTable.getRowCount(); // <--
Object[] currentTasks;
currentTasks = new Object[numTasks];
for (int i = 0; i < numTasks ; i++){
Object tasks = taskTable.getModel().getValueAt(i, 1); // <--
currentTasks[i] = tasks;
}
System.out.println(currentTasks);
}
}
The first will be because delTask itself is null, the second if taskTable is null.
The third will be if taskTable itself is valid but the value returned from its getModel() method is null.
So, it appears that your taskTable is null. As to why this is so, that's unknowable based on the current information. What you will need to do is examine all the places it's set to a valid value and ensure that this happens before you (or more likely, AWT under the control of your user) call this method.
And of course, make sure it's not set back to NULL at some point after creation.
If you can't guarantee that, you'll probably need to change:
if (delTask.isEnabled() == false)
into something like:
if ((! delTask.isEnabled()) && (taskTable != NULL))
but my preference would be to fix the root cause of the problem rather than applying this band-aid.
Your code that creates the JTable seems okay (syntactically) but there's the slight mystery of where that's done. Is it created in a manner that it's usable from where you're trying to use it.
For example, if that code that creates it is within the constructor, that particular taskTable would be local to said constructor (and destroyed on exit), not usable from elsewhere. In that case, it needs to be made an object-level variable so that other methods can get to it.
You can see that effect in the following program:
public class testprog {
public Object thingOne;
public Object thingTwo;
public void someFunction() {
thingOne = new Object();
Object thingTwo = new Object();
}
public void debug() {
if (thingOne == null)
System.out.println ("thingOne is NULL");
else
System.out.println ("thingOne is valid");
if (thingTwo == null)
System.out.println ("thingTwo is NULL");
else
System.out.println ("thingTwo is valid");
}
public static void main(String args[]) {
testprog tp = new testprog();
tp.someFunction();
tp.debug();
}
}
This outputs:
thingOne is valid
thingTwo is NULL
because thje thingTwo set up in someFunction() is a local version and does not in any way set up the object-level thingTwo - the object level one remains as null and, if you try to dereference it, you'll see the same problem you're having.
(a) The best problems reports come with a small, complete code snippet exhibiting the problem, the expected behaviour, and the actual behaviour.
If we post that sample of yours into a naked Eclipse Java program, it's very much not complete. MouseEvent, delTask and taskTable have no definitions and, without that information, it's a little hard to debug.
In addition, Eclipse (for syntax errors) and Java itself (for runtime errors) are perfectly able to tell you in great detail what your problems are, and you should read what it's telling you. You should also communicate that information to us if you want help :-)
Which line is line 233 of ProjectGUI.java? At least one of the following is null:
delTask
taskTable
taskTable.getModel()
Figure out which of those falls on line 233 (per your error report), and you've figured out where the problem lies. We'll need to see more code to determine why the variable does not have the expected value.