Using Reflection in Java

Last semester, my two main programming courses were CS 315 and CS 310 where we learned to use Lisp and LC-3 assembly code respectively. In both, programs and data were of the same format, so modifying a program was as simple as modifying data. In Java, however, it’s a bit more awkward. Sure, you can treat a .java file as text and modify it, but what if you only have the .class file? Or what if you just want an easier way? Fortunately, Java provides a solution called reflection.

In our Software Design course, our first assignment of the semester is to use reflection to create Java programs called adaptors. I’ve just started with the assignment by playing around with the Java reflection library and figuring out how to use these tools, but I thought I’d share a simple example which may be much quicker to understand than the article linked to above.

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    public static void main(String[] args) { 

        // select the class to look into
        Class myclass = String.class;

        // check how many methods the class declares
        Method[] methods = myclass.getDeclaredMethods();
        System.out.println( "Number of methods in "
                + myclass.getName() + " class: " + methods.length + "\n" );

        // select a method from the class
        int methodNum = 52;
        Method mymethod = methods[methodNum];
        System.out.println( "Checking method #" + methodNum + ":" );

        // name of method
        System.out.println( "Name: " + mymethod.getName() );

        // modifiers such as protected or static
        // note: getModifiers() returns an int that you need the Modifier
        //       class to makes sense of
        System.out.println( "Modifiers: "
                + Modifier.toString(mymethod.getModifiers()) );

        // return type of method
        System.out.println( "Return Type: " + mymethod.getReturnType().getName() );

        // list of method's parameters
        Class[] mytypes = mymethod.getParameterTypes();
        for (Class c: mytypes)
            System.out.println( "Parameter: " + c.getName() );
    }
}

The output for this program is:

Number of methods in java.lang.String class: 68

Checking method #52:
Name: substring
Modifiers: public
Return Type: java.lang.String
Parameter: int
Parameter: int

How do you design a favicon?

From all the classes I’ve taken in college, Mike Scott and Don Batory are two of my favorite professors. Aside of being well-prepared for lectures and such, the small details really do matter. The favicons on their websites for CS 307 and CS 378 are fantastic. Whenever I’m scrounging through my bookmarks or just looking among a dozen open tabs, having a quickly recognizable image helps me find just what I’m looking for right away.

A few years ago, I had fun using Gimp for one of the first times in creating the favicon for Chavez360. It was just a smiley face with a red headband. The favicon was very simple, but it symbolized something easily recognizable to any Chavez fan.

This blog is a whole different story, though. Even after almost a year of occasional posts, I don’t have a main focus so a true symbol is out of the question. However, after putting it off for so long, I had to come up with something. Fortunately, I have a short word in the title and used a online favicon generator to come up with something reasonable. Then not knowing what else to put in all the blank space left over, I added in some symmetrical symbols. Adding it to WordPress was simple.

No, it’s not the best favicon in the world, but it sure beats the default icon that Firefox provides so now when I visit, it feels just a little more like home.

Major Oops

Yesterday I discovered the hard way that I had let my domain registration lapse. My credit card number changed a few months ago so the registration couldn’t be renewed, and my contact info was old as well.

When I went to my site to post a few article updates, it was gone. Just a generic landing page with annoying ads instead of the fansite that I had toiled over for so long.

I immediately went to the GoDaddy site to renew my domain as well as my webhosting, which I discovered had also expired. As I was scrambling to type in various numbers, I was thinking to myself: When was the last time I backed up the database? Are all the files on my local machine the same as those that were online when my site was last up? So this is what all those best practices are really about.

Fortunately, shortly after my payment went through, everything was back to normal. All the files, the databases–it was all saved even though GoDaddy could’ve gotten rid of it all if they wanted to. I just have to thank them for making it so easy to get it all back.

Then I went straight to the forum to post an apology to any visitors who had seen that awful page. By evening, there was a response from someone who was afraid I had just given up on the site and was thankful it was back up.

Yep, that’s what makes it all worthwhile.

Semester in Review – Fall ‘09

Ah, my second semester in computer science has finally come to a close. When the Spring semester starts, I’ll no longer be a pre-CS student but a full-fledged CS student. It’s been a very busy semester for me but very rewarding at the same time. I finally feel like I’m at the point where I can comprehend most any topic in CS that anyone cares to throw at me, even though it may still take a little extra time to sink in.

Anyhow, some closing thoughts on the classes that have encompassed me for the past few months:

CS 315: Algorithms and Data Structures (Novak)
Novak’s CS 315 site is one of the best in the department–if for nothing else than having an excellent vocabulary list and so many ways to browse the class notes. Novak wasn’t the most exciting lecturer, but he always made sure we understood what was going on. If I could change one thing about this class, though, I’d like to look at implementations a bit more. He’d tell us that the code already existed, and his focus was on making programming faster and easier for others, but for now I still want to see things very in depth.

CS 310: Computer Organization and Programming (Boral)
In this course, we got to learn the fundamentals. We implemented our own stack and heap using LC-3 and learned how to write machine code. There’s much to be learned from this, but I think the main thing is to cherish the high-level languages we get to use (I still think it’s funny to call C “high-level” though) and to optimize how we use them without having to constantly focus on the small details. Boral was usually an entertaining lecturer, and if it wasn’t for the unpredictability of his tests I’d love to take another course with him.
CS 313K: Logic, Sets, and Functions (Lifschitz)
I took this class ten years ago as Philosophy 313K, so I expected this to be mostly a refresher course, and as such much of it was quite boring. However, I couldn’t miss any lectures because the exams would have questions about topics that weren’t in any of our notes or assignments. The course was mainly focused on mathematical functions and sequences, and I was a bit disappointed that logical quantifiers and connectives weren’t really covered. At least it was a (mostly) easy A for me.
EE 316: Digital Logic Design (Touba)
Between readings, homeworks, and labs, EE 316 is probably the most time-intensive course I’ve taken so far. (The required lab section doesn’t count for any credit hours.) Much of the material looks easy in retrospect, but the pace is so quick that you’re sure to get behind at some point along the way and have a lot of trouble catching up. The verbosity of VHDL is quite irritating, but learning all the tricks with Karnaugh maps was fun and state diagrams seem almost natural now.
M 328K: Introduction to Number Theory (Caputo)
Ah, my last ever pure math course. For being a rather easy course, though, it really made me miss Differential Equations. I mentioned this earlier, and now I’m sure that Moore method isn’t my strong point. I love to research things just to get new ideas even and felt pretty stifled in this class. It looks like what I did learn won’t go to waste, though. I’ve been looking over the supplementary textbook for CS 336 (next semester), and many of the theorems and algorithms I’ve learned are in there. :)

(Note: I’m still waiting for my official grades to come out, but as I’ve calculated it: for the semester I have A’s in CS 310, CS 313k, and M 328k, and B’s in CS 315 and EE 316.
Update: I got an A in CS 315 and an A- in EE 316. Whoo!)

Experience is the best teacher

Some things just take a while to sink in. This summer I was studying my class textbooks in advance because the ideas just simmer in the back of my brain and then make so much more sense when we actually get to them in class. However, my number theory class this semester is different. The class textbook is super thin and holds a few axioms to learn, but then asks us, the students, to explain them and to prove other theorems based on them. Sure, I can read in advance and try to work my way through, but it’s difficult without any feedback. With all these worries, can this still be a better way to learn?

This is a way of teaching known as the Moore method. Instead of the standard lectures, this method allows students to experiment in a way by doing proofs and seeing how what we already know applies to new situations. We all progress at the same rate by presenting what we’ve learned in class and discussing what we did differently or anything that still doesn’t make sense.

Though this method is also used in our logic course, most computer science classes follow the standard lecture and lab format. Professor Gordon Novak told us, “CS is an experimental science,” but by this he didn’t mean that we discover new data structures just by trying to solve a problem and seeing that that would be the best possible solution. Instead with some exceptions, we learn most of the time we don’t need to reinvent the wheel. The focus is on learning about many different data structures, gaining experience using them, and figuring out how to decide which is the best solution to any particular problem.

Of course, the concept of number theory is completely different than most of what we encounter in computer science. The method of proving the theorem (which may be as close to programming as math gets) isn’t so important as the fact that you can prove it and really understand why something’s true. It’s still kind of a shock being in a Moore method class, but it’s only been two weeks, so I still have most of a semester left to see if this works for me.

Getting started with Google AdSense

A year ago, my AdSense application was denied because I had just started a new blog with only a handful of articles and they said my website was still under construction. This time I applied with my more developed hobby site instead and was pleasantly surprised with how easy it was to set up. (I modified the templates directly because I was too impatient to get a plugin working the way I wanted it to.)

After two whole weeks, I’ve earned a whopping $2.13! At this rate, I’ll hit my first $100 payout in just a short couple of years. Now I really wish I had applied again last year instead of putting it off; then I’d already be halfway there. Oh, well. In the end when it’s all averaged out, I’ll have made just enough to cover my hosting costs which makes this a no-cost hobby. There’s nothing better.

Playing with WordPress plugins – Part I

Quite a while back, I wanted to make a quiz site with questions about PHP, and as I’m still into learning more about WordPress, the only logical thing to do is to develop a plugin that will make WordPress into the perfect CMS for this project.

At this moment, there are 5,855 plugins in the WordPress plugin directory. If so many other people have done it, surely it can’t be too hard, right? But I spent countless hours reading the documentation months ago and never had anything to show for it….

Well, this time I’m going agile. I wrote a post asking “What is 2 + 2?”, added a custom field called “correct” with the value 4, and now have the code to make that answer appear underneath the blog entry. It took me a while to figure out that I needed to pass $content to my function to keep the post from disappearing, but it looks like I’m on my way.


add_action( 'the_content', 'the_pop_quiz' );
function the_pop_quiz($content) {
echo $content;
$flif_pid = get_the_ID();
$pop_quiz_answer = get_post_meta( $flif_pid, 'correct', true );
echo $pop_quiz_answer;
}

bbPress 1.0 is finally here!

Hive Bee Honey
Whoa! Two and a half months since my last blog, but bbPress 1.0 just came out recently and I updated the Chavez360 project with this and WordPress 2.8.1, and I finally have a site that integrates as smoothly as I’d like. The only really important suggestion for anybody about to set this up is to install WordPress completely first, including the new bbPress plugin before going on to the bbPress installation. The process would have been a tad smoother for me if only I had thought to do that.

Blogging in DVORAK

Why would anyone who can type 71 wpm in QWERTY want to switch to a different keyboard layout? There are many cases like the guys at DVzine.org who have improved their typing speed by switching, but their speeds in QWERTY were significantly lower than mine. And after a week an a half of using mostly DVORAK when typing, my speed is only around 19 wpm. But then again, switching back to QWERTY occasionally probably doesn’t help.

The hardest part is what to do about all the keyboard shortcuts that were designed for right-handed people with QWERTY. Quite frequently, I’m using Firefox with my right hand on the touchpad. I want to open a link in a new tab, but my left hand still on the keyboard is nowhere near the “t”. And the thought of relearning the muscle memory for all my VIM commands is just painful. That’s why I’ve been switching back and forth a bit too much for the good of my learning.

Oh well, school’s almost out for the summer, at which point I’ll have the extra time to take things slow and see if I really can improve my typing speed with less stress on my hands.

Oracle to Buy Sun

… and I have no idea what this means for MySQL, so I guess this is a short one.

Full press release on Oracle.com.

Ringbinder theme by Themocracy